SQL Escape Tool

-- Escaped Output --

Quick Access to SQL Tools

Go straight to the SQL utility you need.

How to Use the SQL Escape Tool

1

Paste your SQL query

Paste your SQL query.

2

Click Escape

Click Escape.

3

Copy the escaped query

Copy the escaped query.

SQL Escape Tool — Neutralize Dangerous Characters Before They Break Your Query

There's a reason "Bobby Tables" became an internet legend. A student named Robert'); DROP TABLE Students;-- exploited a web form that concatenated user input directly into an SQL query, and the school's entire student database was wiped out. That's not a hypothetical — it's a real attack pattern that still works against applications that don't handle user input properly. The SQL Escape Tool processes text that contains characters with special meaning in SQL — single quotes, backslashes, double quotes, newlines — and transforms them into safe representations that can be embedded in queries without breaking syntax or creating injection vectors.

Run entirely in your browser, the tool takes your raw text, applies configurable escaping rules, and returns a version ready for immediate use in SQL statements. Choose which characters to escape, whether to wrap the output in quotes, and get the result in one click.

Why Escaping Alone Isn't Enough

Escaping is a safety net, not a fortress. The SQL Injection Prevention Cheat Sheet from OWASP is clear: parameterized queries (prepared statements) are the primary defense against injection attacks. When you use a prepared statement, the database engine treats user input as data, never as executable SQL — no matter what characters it contains. Escaping becomes the fallback for situations where prepared statements genuinely aren't available: dynamic SQL construction in stored procedures, ad-hoc query builders that don't support parameterization, or quick one-off scripts where setting up prepared statements is impractical.

Think of it this way: parameterized queries prevent injection at the architectural level. Escaping prevents it at the string level. Architecture wins. But when you can't win architecturally, string-level defense is better than nothing.

Parameterized Queries vs. Escaping: A Clear Comparison

Developers sometimes ask why escaping exists at all if prepared statements are safer. The answer lies in context. A prepared statement sends the SQL template and the data separately to the database. The engine parses the template first, allocates a query plan, and only then binds the data values — never interpreting them as SQL syntax. This two-step process makes injection structurally impossible. Escaping, by contrast, modifies the raw string before it ever reaches the database parser. You're betting that your escaping function handles every possible edge case, every encoding quirk, and every dialect-specific behavior correctly.

Here's a concrete example of the difference. Consider a user entering the input: admin'--. With a prepared statement, the database sees that value purely as a string literal to compare against a column. With escaping, you're relying on the apostrophe being properly doubled to admin''-- so the SQL parser doesn't treat the remaining dashes as a comment. Both approaches produce a safe query, but only one removes the possibility of human error from the equation.

In modern PHP, the PDO extension makes parameterized queries straightforward. In Python, the sqlite3, psycopg2, and mysql-connector libraries all support them natively. Node.js has mysql2 and pg packages with built-in parameter binding. There's rarely a technical reason to prefer escaping over parameterization in application code. Where escaping genuinely earns its keep is in data migration scripts, SQL dump files, stored procedures that build dynamic queries, and situations where you're pasting values into a database client manually.

Characters That Have Special Meaning in SQL

Single quotes ('): SQL uses single quotes to delimit string literals. An unescaped apostrophe in user input — like the name O'Brien — prematurely terminates the string and leaves the rest of the input as executable SQL. The fix is doubling the quote: O''Brien. In standard SQL (PostgreSQL, SQLite, SQL Server), doubling is the only correct escape mechanism.

Backslashes (\): MySQL treats backslash as an escape character by default. A literal backslash in input like C:\Users must be written as C:\\Users to avoid interpreting \U and \s as escape sequences. PostgreSQL ignores backslash escapes unless you specifically enable standard_conforming_strings = off.

Double quotes ("): In standard SQL and PostgreSQL, double quotes delimit identifiers (table and column names). If you're constructing dynamic SQL that includes user-provided table or column names, double quotes need escaping too.

Newlines and control characters: Literal newlines in SQL strings are valid but make query logs hard to read and can cause issues in some client tools. Escaping them as \n (with the database's string escaping mode) or using SQL functions like REPLACE() is more portable.

Null bytes (\0): Particularly dangerous in MySQL because they can truncate strings at the C library level. An attacker who injects a null byte after a security check can cause the database to see a truncated, "safe" value while the full malicious payload remains in memory. Always escape null bytes when targeting MySQL.

Percent and underscore (%, _): These aren't syntactically dangerous in INSERT or UPDATE values, but in LIKE clauses they act as wildcards. If user input ends up in a LIKE comparison without escaping, an attacker can use % to match any sequence or _ to match single characters, potentially extracting data through boolean-based inference. In LIKE contexts, escape % as \% and _ as \_, and specify an ESCAPE clause.

Escaping Differences Across Database Dialects

PostgreSQL is the most predictable: double the single quote, and you're done. Backslashes are treated as literal characters within strings unless you explicitly opt into MySQL-compatible escaping. PostgreSQL also supports escape string syntax (E'...' ) where backslash sequences like \n, \t, and \\ are interpreted — but only within that specific syntax. Regular string literals ('...') never interpret backslashes.

MySQL is more complex: by default, \n, \t, \\, \', \", \0, \%, and \_ are all interpreted as escape sequences inside strings. This means a raw backslash followed by an 'n' becomes a newline, which can silently corrupt data. A path like D:\new_folder inserted without escaping becomes D: followed by a newline and ew_folder. Setting NO_BACKSLASH_ESCAPES mode puts MySQL in standard SQL behavior where backslashes are literal.

SQL Server follows the SQL standard: double single quotes to escape them, and backslashes have no special meaning inside string literals. SQL Server also supports bracket-quoted identifiers ([column name]) and the newer QUOTENAME() function for safely escaping identifiers in dynamic SQL. For string values, the QUOTENAME(@val, '''') trick can double quotes automatically.

SQLite follows standard SQL escaping for single quotes and supports the C-style backslash escape character by default. You can change this behavior with PRAGMA escape_chars in newer versions, or by compiling SQLite with specific flags. In practice, doubling single quotes works universally across SQLite versions.

Special Character Handling Deep Dive

Most developers know to escape single quotes, but several other characters cause real-world bugs when overlooked.

Backslash chains: If your data contains Windows file paths like C:\Program Files\App, each backslash must be doubled for MySQL. Failing to do so doesn't always cause an error — MySQL may silently interpret \P or \A as unknown escape sequences and pass them through, but \n, \t, \r, \0, and \\ will definitely be misinterpreted. The behavior is inconsistent, which makes it a particularly nasty source of data corruption.

Unicode byte sequences: In multi-byte character sets like GBK (used in some Chinese locales), certain byte sequences can form characters that include the ASCII single quote byte (0x27) as part of a multi-byte character. PHP's addslashes() function operates on bytes, not characters, and can split a multi-byte character in half by escaping a byte that's part of a valid character. This was the root cause of a famous MySQL injection bypass. The lesson: always use the database's own escaping functions (mysql_real_escape_string(), pg_escape_string()) rather than hand-rolled byte-level escaping.

Escaped quote stripping: Some ORMs and frameworks automatically strip or unescape quote characters from user input before storing it. This creates a situation where escaping twice (double-escaping) actually produces the correct stored value, but escaping once results in the quotes being stripped. Test your escaping against your specific application stack — don't assume the database is the only layer processing the input.

Semicolons and comment markers: In multi-statement contexts, a semicolon terminates one statement and starts another. An input like '; DROP TABLE users;-- becomes devastating if multi-statement execution is enabled. While this tool focuses on string escaping, be aware that many database connectors disable multi-statement execution by default for exactly this reason. Double-check your connection configuration.

ORM Escaping Behavior: Don't Assume It's Handled

Object-Relational Mappers like Eloquent (Laravel), SQLAlchemy (Python), ActiveRecord (Rails), and Sequelize (Node.js) use parameterized queries by default when you interact with their query builder APIs. Calling User::where('name', $input)->get() in Eloquent produces a prepared statement under the hood — the value is bound as a parameter, not concatenated into the SQL string.

The danger arises when developers bypass the ORM's safe APIs. Raw queries like DB::select("SELECT * FROM users WHERE name = '$input'") in Laravel, or cursor.execute(f"SELECT * FROM users WHERE name = '{input}'") in Python's sqlite3 module, skip parameterization entirely. These raw queries are where injection attacks live. Even if you're using an ORM, always verify that the specific query method you're calling actually uses parameterization — and when in doubt, use the parameter binding syntax provided by your ORM.

Another common mistake is using ORM functions like whereRaw() or selectRaw() with string interpolation. These methods accept raw SQL fragments, and if you interpolate user input directly into them, you've reintroduced the exact vulnerability the ORM was designed to prevent. The fix: use parameter binding within raw methods. In Laravel, whereRaw('name = ?', [$input]) is safe; whereRaw("name = '$input'") is not.

Character Set Considerations

Character encoding plays a bigger role in SQL escaping than most developers realize. When your database connection uses a multi-byte character set like UTF-8, GBK, or Big5, the bytes that make up a character may overlap with bytes that have special meaning in SQL. This is the multibyte encoding attack.

The most well-documented example involves MySQL's GBK encoding. The single quote character (0x27 in ASCII) happens to be the second byte of certain GBK characters. A well-crafted GBK string can contain an "escaped" single quote that addslashes() doesn't catch because it only looks at individual bytes, not character boundaries. The result: the string literal is terminated prematurely, and injection succeeds.

Modern mitigations include: using MySQL's mysql_real_escape_string() which is charset-aware (it knows the connection's encoding and escapes correctly), setting the connection charset to UTF-8 explicitly with SET NAMES utf8mb4, and using parameterized queries which sidestep the encoding issue entirely. If you're maintaining a legacy codebase that uses addslashes() or manual string replacement, switching to parameterized queries is the single highest-impact security improvement you can make.

Always ensure that your application, database connection, and database tables all agree on character encoding. Mismatched encodings can cause escaping to silently fail — your application might escape a UTF-8 string, but the database interprets it as latin1, splitting characters at different byte boundaries and potentially un-escaping what you thought was protected.

Escaping in Stored Procedures

Stored procedures often need to build dynamic SQL — constructing query strings from parameters passed to the procedure. This is one of the few legitimate scenarios where escaping is the primary defense rather than a supplement to parameterized queries, because the dynamic SQL itself can't be a prepared statement in most implementations (though SQL Server and PostgreSQL do support sp_executesql and EXECUTE ... USING for parameterized dynamic SQL).

When building dynamic SQL in a stored procedure, the escaping function you use depends on the database engine. In SQL Server, use QUOTENAME() for identifiers and REPLACE() with quote-doubling for string values, or use sp_executesql with parameters. In PostgreSQL, use the quote_literal() and quote_ident() built-in functions. In MySQL, PREPARE/EXECUTE with parameter binding is available within stored procedures and should be preferred over string concatenation.

A common anti-pattern in stored procedures is building a WHERE clause by concatenating a fixed column name with user-supplied values that haven't been escaped. For example: SET @sql = CONCAT('SELECT * FROM orders WHERE customer = ''', @name, ''''). If @name contains a single quote, the query breaks — or worse, it succeeds with unintended results. Always escape or parameterize values in dynamic SQL, even inside stored procedures.

When to Use This Tool vs. a Prepared Statement

Use escaping when: you're writing a one-off data migration script, building SQL dynamically in a stored procedure, pasting a value into a query builder that doesn't support parameterization, preparing a value for a SQL file that will be imported via a CLI tool, or populating test data in a database client that doesn't support parameter binding. Use prepared statements when: you're building any application that accepts user input — web forms, APIs, CLI tools, desktop apps. Prepared statements are faster (the database can cache the query plan), safer (input is never interpreted as SQL), and more maintainable (no escaping logic to maintain).

Frequently Asked Questions

Escaping significantly reduces the risk but is not a complete defense on its own. Sophisticated attacks can exploit edge cases in escaping logic, character encoding mismatches (like GBK encoding bypassing MySQL's addslashes), or dialect-specific behaviors. The definitive defense is parameterized queries with bound placeholders. Use escaping as a supplementary measure — for SQL files, stored procedures, or situations where prepared statements genuinely can't be used.
In PostgreSQL, you double single quotes and leave backslashes alone. That's it — clean and predictable. MySQL, by default, interprets backslashes as escape characters, meaning a literal \ must become \\, and \n in input becomes a newline. MySQL also interprets \0 (null byte), \', \", and \% as escapes. If you disable MySQL's NO_BACKSLASH_ESCAPES mode, it behaves like PostgreSQL. Know your server's mode before deciding which escaping strategy to use.
SQL string values must be enclosed in single quotes: WHERE name = 'O''Brien'. If you're escaping a value to use in a string context — INSERT, UPDATE SET, WHERE comparisons — wrap it in single quotes. If you're escaping an identifier (table or column name), use double quotes in standard SQL or backticks in MySQL. Choose "no wrapping" when you'll add quotes manually, when the escaped value will be concatenated into a larger string, or when it's a numeric value that doesn't need quoting.
Yes. Unicode characters — including CJK scripts, Arabic, Cyrillic, emoji, and combining characters — pass through the escaping process untouched. Only the specific characters you've configured for escaping (single quotes, backslashes, etc.) are modified. The tool preserves the original encoding of all other characters.
Table and column names are identifiers, not string values, so they use different escaping rules. In standard SQL and PostgreSQL, wrap identifiers in double quotes ("order"). In MySQL, use backticks (`order`). In SQL Server, use brackets ([order]). This tool focuses on string value escaping. For identifier quoting, use the appropriate delimiter for your dialect — and ideally, avoid dynamic identifiers entirely since they can't be parameterized.
Yes. Escape each value individually, then assemble your INSERT statement. For large datasets with many rows, consider using a prepared statement with bound parameters instead — it's faster, safer, and you avoid the escaping step entirely. If you're working with raw SQL files where prepared statements aren't an option, escaping each value before pasting it into the INSERT is the correct approach.
Null bytes (\0) are particularly dangerous in MySQL because they can truncate strings at the C language level, potentially bypassing security checks. An attacker might inject admin\0password where the null byte terminates the string after "admin" in low-level string handling, but the full payload remains in memory. The tool's backslash escaping option handles null bytes. Control characters like carriage returns (\r) and tabs (\t) are preserved unless you've enabled newline escaping, in which case they're converted to their escape sequence equivalents.
The escaping rules are the same — single quotes doubled, backslashes doubled where applicable. The context doesn't change the escaping logic. What does change is how you use the result: in a WHERE clause, the escaped value goes inside the comparison (WHERE name = 'O''Brien'); in an INSERT VALUES, it goes inside the value list. The escaping itself is identical in both cases.
Partially. The tool escapes single quotes, backslashes, and other characters that are dangerous in string literals — which you still need for LIKE values. However, LIKE clauses have two additional wildcard characters (% and _) that need escaping only in the LIKE context. If your input contains literal percent signs or underscores that should be treated as themselves rather than wildcards, you'll need to escape them separately with a LIKE '%' escape clause in your query, or use the database's built-in ESCAPE keyword (e.g., WHERE col LIKE '100\%' ESCAPE '\').
Most modern databases offer built-in functions for this. PostgreSQL provides quote_literal() for string values and quote_ident() for identifiers. SQL Server supports QUOTENAME() and sp_executesql with parameter binding even inside stored procedures. MySQL supports PREPARE/EXECUTE statements with ? placeholders within stored procedures. Use these built-in mechanisms rather than hand-rolling escape logic — they're tested, maintained, and account for the specific database's encoding and escape rules. If none of these are available for your use case, this tool can help you escape individual values before embedding them in dynamic SQL.