How to insert a value that contains an apostrophe (single quote)?
What is the correct SQL syntax to insert a value with an apostrophe in it?
Insert into Person
(First, Last)
Values
'Joe',
'O'Brien'
I keep getting an error as I think the apostrophe after the O is the ending tag for the value.
Solution 1:
Escape the apostrophe (i.e. double-up the single quote character) in your SQL:
INSERT INTO Person
(First, Last)
VALUES
('Joe', 'O''Brien')
/\
right here
The same applies to SELECT queries:
SELECT First, Last FROM Person WHERE Last = 'O''Brien'
The apostrophe, or single quote, is a special character in SQL that specifies the beginning and end of string data. This means that to use it as part of your literal string data you need to escape
the special character. With a single quote this is typically accomplished by doubling your quote. (Two single quote characters, not double-quote instead of a single quote.)
Note: You should only ever worry about this issue when you manually edit data via a raw SQL interface since writing queries outside of development and testing should be a rare occurrence. In code there are techniques and frameworks (depending on your stack) that take care of escaping special characters, SQL injection, etc.
Solution 2:
You just have to double up on the single quotes...
insert into Person (First, Last)
values ('Joe', 'O''Brien')
Solution 3:
You need to escape the apostrophe. In T-SQL this is with a double apostrophe, so your insert
statement becomes:
Insert into Person
(First, Last)
Values
'Joe', 'O''Brien'
Solution 4:
Because a single quote is used for indicating the start and end of a string; you need to escape it.
The short answer is to use two single quotes - ''
- in order for an SQL database to store the value as '
.
Look at using REPLACE to sanitize incoming values:
- Oracle REPLACE
- SQL Server REPLACE
- MySQL REPLACE
- PostgreSQL REPLACE
You want to check for ''''
, and replace them if they exist in the string with ''''''
in order to escape the lone single quote.
Solution 5:
Single quotes are escaped by doubling them up,
The following SQL illustrates this functionality.
declare @person TABLE (
[First] nvarchar(200),
[Last] nvarchar(200)
)
insert into @person
(First, Last)
values
('Joe', 'O''Brien')
select * from @person
Results
First | Last
===================
Joe | O'Brien