SQL String Escape
Escape special characters in SQL strings to prevent SQL injection attacks
About SQL String Escaping
SQL string escaping is the process of converting special characters in strings into escape sequences for safe use in SQL queries. Most importantly, single quotes must be escaped as they delimit SQL string literals.
Proper SQL escaping is the first line of defense against SQL injection attacks. SQL injection is one of the most common and dangerous web security vulnerabilities, where attackers can construct malicious input to execute unauthorized database operations.
Security Warning
While escaping can help prevent SQL injection, the best practice is to use parameterized queries (prepared statements). Escaping should be an additional security layer, not the only protection measure.
Escape Rules (Standard SQL)
| Original Character | Escape Sequence | Description |
|---|---|---|
| ' | '' | Single quote (doubled) |
| \ | \\ | Backslash (MySQL) |
Database Differences
MySQL
Supports backslash escaping (\' and \\), also supports standard SQL double single-quote escaping
PostgreSQL
Standard mode uses double single-quotes, can also use E'...' syntax to enable backslash escaping
SQL Server
Only supports double single-quote escaping, does not support backslash escaping
Oracle
Uses double single-quote escaping, can also use q'[...]' alternative quoting syntax
Security Recommendations
- Always prefer parameterized queries over string concatenation
- Validate and sanitize user input
- Use escape functions provided by database drivers
- Limit database user permissions, follow principle of least privilege
- Regularly conduct security audits and code reviews