SQL Server
SELECT * FROM users WHERE last_name = 'O''Brien';
Doubling is the only escape. QUOTENAME(@s, '''') produces a quoted, doubled literal when building dynamic SQL, but it returns NULL for input over 128 characters.
Doubling the quote works everywhere; three engines offer nicer ways out.
Filed under Querying
'O''Brien' is the one form that runs on all five engines. In application code, bind the value as a parameter and the question goes away. The engine-specific literal styles are for scripts, migrations and debugging, not for escaping user input by hand, which is how SQL injection happens.
In every dialect, a single quote inside a literal is written as two single quotes: 'O''Brien'. MySQL also accepts a backslash escape, PostgreSQL has dollar-quoting and E'' strings, and Oracle has q-quoted literals. SQL Server and SQLite have only the doubling rule.
SELECT * FROM users WHERE last_name = 'O''Brien';
Doubling is the only escape. QUOTENAME(@s, '''') produces a quoted, doubled literal when building dynamic SQL, but it returns NULL for input over 128 characters.
SELECT * FROM users WHERE last_name = 'O''Brien';
Dollar-quoting skips the doubling: $$O'Brien$$. E'O\'Brien' is the backslash-escape form; in a plain literal, backslash is an ordinary character.
SELECT * FROM users WHERE last_name = 'O''Brien';
'O\'Brien' also works unless sql_mode includes NO_BACKSLASH_ESCAPES. Double-quoted strings work too unless ANSI_QUOTES is set.
SELECT * FROM users WHERE last_name = 'O''Brien';
Doubling is the only escape; a backslash in a literal is just a backslash.
SELECT * FROM users WHERE last_name = 'O''Brien';
q'[O'Brien]' lets you pick the delimiters ([], {}, <>, () or any single character), which helps with text full of quotes.
The parser takes the quote in O'Brien as the end of the literal, so 'O' becomes the string and Brien' becomes the start of a syntax error. That same mechanism is what SQL injection exploits. Two quotes in a row ('') put one literal quote in the string.
A PostgreSQL literal: $$O'Brien$$ ends only at the closing $$, so nothing inside needs escaping. Add a tag, as in $body$…$body$, when the text itself contains $$. It is PostgreSQL-only and mostly used for function bodies.
No. Bind parameters. Hand escaping breaks on edge cases such as MySQL's backslash mode or multibyte encodings, and it is the classic injection hole. Keep it for one-off scripts you type yourself.
Same task, three operators, and the NULL rules differ between them.
% and _ are wildcards until you declare an escape character, and backslash is the worst choice for one.
Four engines ship regex today, SQL Server only since 2025; SQLite leaves it to the application.
SQLly is a native SQL workbench for macOS, Windows and Linux. Its formatter and plan viewer work in all five dialects.