473

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
leora
  • 188,729
  • 360
  • 878
  • 1,366
  • 23
    Please confirm that you're not opening yourself up to SQL injection attacks. Use parameters where at all possible. – Andrew Dec 16 '09 at 03:41
  • What scripting language are you using? There are functions in PHP, for example, to do this correctly for you. – philfreo Dec 16 '09 at 04:21
  • Agreeing with Andrew here: I hope this question is only in regards to running SQL via a SQL client or "query browser" or such and not actually somewhere in production code. Not using parameterized statements is folly. – charstar Dec 16 '09 at 05:39
  • it actually is in code.. if i had a parameterized query wouldn't i have to do the same thing ? – leora Dec 16 '09 at 08:02
  • 3
    Negative. Depending on the database and the driver you are using, isolation of the parameters might be handled differently, but parameters in a parameterized statement do not require escaping. See http://en.wikipedia.org/wiki/SQL_injection#Preventing_SQL_injection – charstar Dec 16 '09 at 19:47
  • PHP: If data with quoted text is stored in variable say $data, then do this "$data = str_replace("'","''",$data);" – Shine Cardozo Jul 25 '15 at 09:45

13 Answers13

701

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Paul Sasik
  • 79,492
  • 20
  • 149
  • 189
  • 8
    $linkQuestion = str_replace ("'","''", $linkQuestion);(gosh that's hard to read!) – user462990 May 03 '16 at 13:52
  • what if the data is Insert into Person (First, Last) Values 'Joe', 'Father's shop' . – vijesh Mar 18 '20 at 11:52
  • This doesn't help if you have to do this through a script, as vijesh mentions. Let's assume the string literal in unalterable. How then do you work with it? – Jamesckel Sep 28 '20 at 18:39
60

You just have to double up on the single quotes...

insert into Person (First, Last)
values ('Joe', 'O''Brien')
Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
38

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'
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
David Hall
  • 32,624
  • 10
  • 90
  • 127
  • 1
    AFAIK the `Values` must be enclosed in braces (which then makes it the same answer as that of @JustinNiessner) – qwerty_so Jun 28 '15 at 14:28
23

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:

You want to check for '''', and replace them if they exist in the string with '''''' in order to escape the lone single quote.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
OMG Ponies
  • 325,700
  • 82
  • 523
  • 502
18

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
Max Pringle
  • 621
  • 6
  • 18
7

The apostrophe character can be inserted by calling the CHAR function with the apostrophe's ASCII table lookup value, 39. The string values can then be concatenated together with a concatenate operator.

Insert into Person
  (First, Last)
Values
  'Joe',
  concat('O',char(39),'Brien')
Nathan
  • 3,082
  • 1
  • 27
  • 42
6

eduffy had a good idea. He just got it backwards in his code example. Either in JavaScript or in SQLite you can replace the apostrophe with the accent symbol.

He (accidentally I am sure) placed the accent symbol as the delimiter for the string instead of replacing the apostrophe in O'Brian. This is in fact a terrifically simple solution for most cases.

Community
  • 1
  • 1
Robert Sherman
  • 391
  • 4
  • 6
  • Great and much simpler solution and my last name is O`Reilly! – PhillipOReilly Nov 06 '18 at 01:23
  • Anyways It is advised to use escape characters . Accidently :) since the day I am using keyboard . I am using accent symbol unintentionally in place of single quote while writing documents. (however in code I use ' as char identifier). Until last year when somebody told me his password and I was unable to login in to his system. we could not figure out until hours that I am typing ' as `. – Learner Apr 11 '19 at 08:48
2

use double quotation marks around the values.

insert into Person (First, Last) Values("Joe","O'Brien")
run_time_error
  • 697
  • 1
  • 8
  • 22
  • 3
    Note that this is not standard SQL any more, though I know Informix, to name but one DBMS, allows it. You should also address how you'd insert a string such as `He said, "Don't!"` using single quotes and/or double quotes — which can be done: `'He said, "Don''t!"'` or `"He said, ""Don't!"""`. When adding a new answer to a long-established question with accepted answers, you must provide new, complete information. Using double quotes is new — but limited to a few DBMS; you should take pains to identify at least one of those that does accept them. – Jonathan Leffler May 30 '17 at 07:23
2

Another way of escaping the apostrophe is to write a string literal:

insert into Person (First, Last) values (q'[Joe]', q'[O'Brien]')

This is a better approach, because:

  1. Imagine you have an Excel list with 1000's of names you want to upload to your database. You may simply create a formula to generate 1000's of INSERT statements with your cell contents instead of looking manually for apostrophes.

  2. It works for other escape characters too. For example loading a Regex pattern value, i.e. ^( *)(P|N)?( *)|( *)((<|>)\d\d?)?( *)|( )(((?i)(in|not in)(?-i) ?(('[^']+')(, ?'[^']+'))))?( *)$ into a table.

Daniel Rust
  • 514
  • 5
  • 4
  • 2
    Is this answer Oracle-Specific? I can't find anything online about this working with SQL, and this PC I'm on doesn't use SSMS. Got a link for Microsoft SQL? Then, how do you insert `that's what she said ]' etc` ? Does the existence of a square bracket, and possibly followed by a single tick, tell it to break the value? – Suamere Oct 03 '20 at 14:25
  • Hi @Suamere, I use Oracle so I had to search the web to tell if this is specific or not to it... I found very little about the subject indeed. [This acticle](https://www.geeksforgeeks.org/sql-alternative-quote-operator/) suggests it's specific to Oracle. But there might be a different approach for other vendors... – Daniel Rust Oct 05 '20 at 08:30
2

If it is static text, you can use two single quote instead of one as below:

DEC @text = 'Khabir''s Account'

See after Khabir there are two single quote ('')

If your text is not static and it is passed in Store procedure parameter then

REPLACE(@text, '''', '')
Khabir
  • 5,370
  • 1
  • 21
  • 33
1

This is how my data as API response looks like, which I want to store in the MYSQL database. It contains Quotes, HTML Code , etc.

Example:-

{

rewardName: "Cabela's eGiftCard $25.00",

shortDescription: '<p>adidas gift cards can be redeemed in over 150 adidas Sport Performance, adidas Originals, or adidas Outlet stores in the US, as well as online at&nbsp;<a href="http://adidas.com/">adidas.com</a>.</p>

terms: '<p>adidas Gift Cards may be redeemed for merchandise on&nbsp;<a href="http://adidas.com/">adidas.com</a>&nbsp;and in adidas Sport Performance, adidas Originals, and adidas Outlet stores in the United States.'

}

SOLUTION

CREATE TABLE `brand` (
`reward_name` varchar(2048),
`short_description` varchar(2048),
`terms` varchar(2048),  
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;

While inserting , In followed JSON.stringify()

    let brandDetails= {
    rewardName: JSON.stringify(obj.rewardName),  
    shortDescription: JSON.stringify(obj.shortDescription),
    term: JSON.stringify(obj.term),
     }

Above is the JSON object and below is the SQL Query that insert data into MySQL.

let query = `INSERT INTO brand (reward_name, short_description, terms) 
VALUES (${brandDetails.rewardName}, 
(${brandDetails.shortDescription}, ${brandDetails.terms})`;

Its worked....

enter image description here

Ajay
  • 176
  • 6
0

Use a backtick (on the ~ key) instead;

`O'Brien`
eduffy
  • 39,140
  • 13
  • 95
  • 92
  • 1
    Then the problem becomes: how to insert a backtick? – Jasper de Vries Apr 24 '17 at 08:46
  • 1
    While this is not the "right" answer, I'm working with a set of names that don't have this, and I'm doing one off operations, so this immediately solved my problem. Thanks! – nscalf Mar 16 '20 at 14:41
  • It's not on the ~ key on my keyboard. UK PC keyboards have it on a button of its own to the left of number `1` key. – Caltor Jul 25 '22 at 08:37
0

the solution provided is not working fine, since it ads the string with two single quote in database, the simplest way is to use anti back slash before the apostrophe (single quote).

Insert into Person  (First, Last) Values  'Joe',  'O\'Brien'
mehdigriche
  • 444
  • 1
  • 4
  • 14