Skip to content
Buy me a coffee
String Escaper & Utilities

SQL Escape / Unescape

Escapes or unescapes a SQL string, doubling single quote characters that could prevent execution.

Standard doubling works in every database. Backslash escaping is a MySQL/MariaDB extension (when NO_BACKSLASH_ESCAPES is off).
Escaping is not a defense against SQL injection

Use prepared statements / parameterized queries to pass values to your database. Escape by hand only for literal values written directly into a script or migration.

Ctrl + Enter

SQL string escaping explained

Why escape?

In SQL a string literal is delimited by single quotes. A single quote inside the value would terminate the literal early and either cause a syntax error or, much worse, let the rest of the value be executed as SQL. The standard way to represent a literal single quote is to double it: ''.

-- The value:      a single quote ' is offensive
select * from table where value = 'a single quote '' is offensive';

Rules applied by this tool

CharacterStandard SQLMySQL backslash style
Single quote '''\'
Double quote "unchanged\"
Backslash \unchanged\\
Newline (U+000A)unchanged (literal line break)\n
Carriage return (U+000D)unchanged\r
Null character (U+0000)unchanged\0
Control-Z (U+001A)unchanged\Z

The standard style (ANSI SQL-92) is understood by every relational database: PostgreSQL, SQL Server, Oracle, SQLite, DB2, MySQL and MariaDB. The backslash style is a MySQL extension, equivalent to what mysqli_real_escape_string() produces; it is disabled when the NO_BACKSLASH_ESCAPES SQL mode is on, and PostgreSQL only honours it inside E'…' strings.

Before / after

InputStandard SQLMySQL style
O'ReillyO''ReillyO\'Reilly
it's a 'test'it''s a ''test''it\'s a \'test\'
C:\tempC:\tempC:\\temp
Two lines separated by a line breakunchangedline one\nline two

Use prepared statements, not escaping

Escaping only protects string literals. It does nothing for numbers, identifiers, LIKE wildcards (% and _), multi-byte encoding tricks or a value that is later used in dynamic SQL. Every modern database driver supports parameterized queries: the SQL text and the values travel separately and the server never has to parse user data as SQL. This is the only reliable defense against SQL injection.

-- Java (JDBC)
PreparedStatement ps = con.prepareStatement("select * from t where value = ?");
ps.setString(1, userInput);

-- PHP (PDO)
$stmt = $pdo->prepare('select * from t where value = :v');
$stmt->execute(['v' => $userInput]);

-- Python (psycopg / sqlite3)
cur.execute("select * from t where value = %s", (user_input,))

-- Node.js (pg)
await client.query('select * from t where value = $1', [userInput]);

Hand escaping remains useful for values you type yourself into seed scripts, fixtures and migrations, which is exactly what this tool is for.