SQL escape/unescape refers to the process of sanitizing text input so it can be safely embedded in SQL statements.
Escaping modifies special characters (like quotes or backslashes) in a way that prevents syntax errors or malicious code execution.
Unescaping converts the escaped characters back to their original form, usually for display or further processing.
To prevent SQL injection attacks, where malicious input can alter the logic of an SQL query.
To avoid syntax errors in queries when data contains characters like ', ", or \.
To maintain data integrity, ensuring that user input is stored and retrieved exactly as entered.
Escaping is done by:
Doubling single quotes in strings (e.g., 'O'Brien' becomes 'O''Brien').
Using built-in database functions or libraries to escape inputs properly.
Unescaping occurs when retrieving the data, often handled automatically by the database or your application layer.
In modern development, this is typically managed by parameterized queries or ORMs (Object-Relational Mappers), which handle escaping securely and automatically.
When inserting or querying user input directly in raw SQL (not recommended unless properly escaped).
When dealing with legacy systems or raw SQL strings where automatic protection isn't in place.
Always escape inputs unless using prepared statements or parameterized queries, which are the preferred and safer alternatives.