SQL Escape Single Quote

Galaxy Glossary

How do you insert data containing single quotes into a SQL database?

SQL uses single quotes to delimit string literals. If your data itself contains a single quote, you need to escape it to avoid syntax errors. This is done using a backslash.
Sign up for the latest in SQL knowledge from the Galaxy Team!
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.

Description

In SQL, string values are enclosed within single quotes. However, if your data string contains a single quote ('), SQL will interpret this as the end of the string literal, leading to a syntax error. To prevent this, you need to escape the single quote within the string. The most common method is to use a backslash (\) before the single quote. This tells SQL to treat the single quote as a literal character within the string, rather than as a string delimiter.Imagine you want to insert the phrase 'O'Reilly Media' into a database column. Without escaping the single quote within the string, the SQL statement would be invalid. Using the backslash escape character, you can correctly represent the string within the database.This is a crucial concept for data integrity. If you don't escape single quotes, your data might not be stored correctly, leading to errors in queries and applications that use the data. It's essential to understand this technique for inserting and retrieving data containing special characters, such as single quotes, apostrophes, or other reserved characters.

Why SQL Escape Single Quote is important

Escaping single quotes is fundamental for data integrity. It prevents SQL syntax errors when dealing with strings containing special characters. Without proper escaping, data insertion and retrieval can fail, leading to application issues.

Example Usage


-- Delete all orders placed before January 1, 2023
DELETE FROM Orders
WHERE OrderDate < '2023-01-01';

-- Delete the order with order ID 1001
DELETE FROM Orders
WHERE OrderID = 1001;

-- Delete all orders from a specific customer (CustomerID = 123)
DELETE FROM Orders
WHERE CustomerID = 123;

-- Important:  This will delete all rows from the Orders table!
-- DELETE FROM Orders;  -- Use with extreme caution!

Common Mistakes

Want to learn about other SQL terms?