SQL escape apostrophe

In SQL Server, escaping apostrophes is an important consideration when dealing with string literals to ensure the proper handling of single quotes within the text. The single quote character is used to delimit string literals in SQL, so if your string contains a single quote, you need to escape it to avoid syntax errors or unintended behavior.

Example

The most common way to escape a single quote in SQL Server is by using two consecutive single quotes (”). Here’s an example to illustrate:

-- Creating a table with a column containing a string with a single quote
CREATE TABLE ExampleTable (
    ID INT,
    Description NVARCHAR(100)
);

-- Inserting data with a single quote and escaping it
INSERT INTO ExampleTable (ID, Description) VALUES
(1, 'This is an example with a single quote (''apostrophe'')');

-- Querying the data
SELECT * FROM ExampleTable;

In the example above, the string ‘This is an example with a single quote (”apostrophe”)’ contains a single quote within the word “apostrophe.” To escape the single quote, we use two consecutive single quotes (”). This tells SQL Server to treat it as a single quote within the string rather than as the end of the string.

Let’s say you have a string that contains an apostrophe, such as “John’s car”. In SQL Server, you would represent this string by enclosing it in single quotes. However, since the string itself contains a single quote, you need to escape it by doubling it:

INSERT INTO ExampleTable (ID, Description)
VALUES (2, 'John''s car');

This tells SQL Server that the apostrophe within the string is not the end of the string but is a part of the actual data.

It’s important to note that different database systems may have different ways of escaping characters, so the method mentioned here is specific to SQL Server. Always refer to the documentation of the database system you are using to ensure proper syntax and handling of special characters in SQL queries.