Skip to main content
Database Administration & Troubleshooting

SQL Query Escape Single Quote: Syntax, Methods, and Examples

Escaping a single quote in SQL prevents syntax errors when a string literal contains an apostrophe. The standard method uses two single quotes ('') inside the string, supported by all major databases.

INSERT INTO customer (id, customer_name) VALUES (502, 'Lay''s');

Why does the SQL single quote escape error occur?

  • String delimiter conflict: Single quotes delimit string literals; an unescaped quote terminates the string prematurely.
  • Dynamic SQL generation: Building queries with concatenated user input often introduces unescaped quotes.
  • Missing alternate delimiters: Some databases (Oracle, PostgreSQL) support alternative quoting (q'[...]', $quote$) that eliminate the need to escape.
  • Improper client-side escaping: Application layers like Python, Java, or .NET may double-escape or fail to escape before sending to the database.
  • SET QUOTED_IDENTIFIER OFF side effects: In SQL Server, disabling this setting changes how double quotes behave, often causing confusion with single quotes.

The error typically manifests as a syntax error near the misplaced quote or as an incomplete string. It is most common when inserting names like O'Brien or Lay's.

Common mistakes

  • Using a backslash to escape – SQL Server and Oracle do not treat backslash as an escape character by default; use two quotes instead.
  • Forgetting to escape in LIKE patterns – Single quotes inside a LIKE pattern must still be doubled; the wildcard characters (%, _) are separate.
  • Mixing single and double quotes – SET QUOTED_IDENTIFIER ON (default) treats double quotes as identifiers, not strings. Using double quotes for strings in SQL Server raises errors.
  • Not escaping in dynamic SQL within stored procedures – Inside EXEC() or sp_executesql, you may need to double the quotes again to avoid syntax errors.
  • Assuming REPLACE() automatically escapesREPLACE(string, '''', '''''') works but is error-prone if the input contains an odd number of quotes.
See also  Union In SQL: Syntax, Examples, Flags & Production Guide

How to escape a single quote in SQL

  1. Double the single quote – Replace each single quote with two single quotes (''). This is the ANSI/ISO standard method.
  2. Use the CHAR() function – In SQL Server and Oracle, append CHAR(39) to represent a single quote.
  3. Use alternative quoting syntax – Oracle: q'[delimiter]'; PostgreSQL: $$ dollar quoting; MySQL: ' with NO_BACKSLASH_ESCAPES off.
  4. Use QUOTENAME() in SQL Server – Wraps a string in brackets, but also escapes quotes if used with a delimiter argument.
  5. Use prepared statements/parameterized queries – The database driver handles escaping automatically; avoid string concatenation.
Method Example Database(s)
Double single quote 'O''Brien' All
CHAR(39) concatenation 'O' + CHAR(39) + 'Brien' SQL Server, Oracle
Alternative quotes q'[O'Brien]' (Oracle) or $$O'Brien$$ (PostgreSQL) Oracle, PostgreSQL
QUOTENAME() QUOTENAME('O''Brien', '''') SQL Server
Prepared statement EXEC sp_executesql N'SELECT name FROM users WHERE name = @name', N'@name nvarchar(50)', @name = 'O''Brien' SQL Server (client-side)

Performance Considerations

The QUOTED_IDENTIFIER setting affects how SQL Server parses string literals and identifiers. When QUOTED_IDENTIFIER ON (default), double quotes are reserved for identifiers, forcing single quotes for strings. This eliminates parsing ambiguity and avoids re-evaluation overhead. As noted in official forums, the EXEC command for dynamic SQL should use parameterized queries to cache execution plans and avoid re-parsing.

-- Check current QUOTED_IDENTIFIER status
SELECT SESSIONPROPERTY('QUOTED_IDENTIFIER');

-- Toggle per session
SET QUOTED_IDENTIFIER ON;

-- Example of parameterized EXEC
EXEC sp_executesql N'SELECT * FROM users WHERE name = @name', N'@name nvarchar(50)', @name = 'O''Brien';

Security and Operational Best Practices

  • IAM / Least-Privilege: Create database users with read-only or CRUD roles scoped to specific tables. Never use sa or root for web applications. For cloud databases, use IAM roles that restrict access to production schemas.
  • Authentication Knobs: Enforce parameterized queries (prepared statements) over manual escaping. In SQL Server, ensure SET QUOTED_IDENTIFIER ON is default. For MySQL, use mysqli real_escape_string only as a fallback. Configure SSL/TLS for all client-server connections to prevent MITM tampering.
  • Audit / Logging Hooks: Enable database query logging to capture all INSERT/SELECT statements. Use system audit tools to monitor configuration changes and failed escape attempts.
See also  Concat In SQL: Syntax, Flags, Examples & Troubleshooting Guide

Frequently Asked Questions

What is the difference between using backslash escaping and parameterized queries for single quotes?

Answer: Backslash escaping (') is dialect-specific and prone to injection; parameterized queries (prepared statements) are universal and secure.

Backslash escaping works in MySQL with NO_BACKSLASH_ESCAPES off, but fails in PostgreSQL (uses '' double single quotes). Parameterized queries separate data from code. Example of MySQL backslash: INSERT INTO customer (id, customer_name) VALUES (502, 'Lay's');

When should I use the REPLACE function instead of doubling single quotes?

Answer: Use REPLACE when you cannot control the input string variable, like dynamic SQL in stored procedures.

Doubling single quotes ('') works for literals in static queries, but dynamic SQL requires sanitization. In T-SQL: SET @sql = 'SELECT * FROM users WHERE name = ''' + REPLACE(@name, '''', '''''') + ''''; However, parameterized queries are safer.

How do I fix “SQLSTATE[42000]: syntax error due to unescaped single quote in PHP PDO?”

Answer: Use PDO prepared statements with placeholders; never escape manually.

The error occurs when concatenating user input directly. Use $stmt = $pdo->prepare("SELECT * FROM users WHERE name = :name"); $stmt->execute([':name' => "O'Brien"]); Avoid mysql_real_escape_string() with PDO; it contradicts the purpose.

How do I escape a single quote in Oracle using alternative quoting?

Answer: Use the q'[...]' syntax where the delimiter can be any character not appearing in the string.

Example: INSERT INTO customer (id, customer_name) VALUES (502, q'[Lay's]'); This works in Oracle 10g+ and eliminates the need to double quotes.