// dialect comparison

Escaping single quotes in string literals

Doubling the quote works everywhere; three engines offer nicer ways out.

Filed under Querying

The verdict

'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.

Where they differ

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.

How each engine writes it

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.

PostgreSQL

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.

MySQL

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.

SQLite

SELECT * FROM users WHERE last_name = 'O''Brien';

Doubling is the only escape; a backslash in a literal is just a backslash.

Oracle

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.

Questions that come up

Why does one quote break the whole query?

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.

What is dollar-quoting?

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.

Shouldn't I just sanitize quotes in application code?

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.

Keep reading

// write it once, run it anywhere

Switch engines without relearning SQL

SQLly is a native SQL workbench for macOS, Windows and Linux. Its formatter and plan viewer work in all five dialects.