Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 838
leora Avatar asked Dec 16 '09 03:12

leora


People also ask

How do you insert apostrophes?

An apostrophe is a small punctuation mark ( ' ) placed after a noun to show that the noun owns something. The apostrophe will always be placed either before or after an s at the end of the noun owner. Always the noun owner will be followed (usually immediately) by the thing it owns.

How do I insert data into a single quote in Oracle?

The most simple and most used way is to use a single quotation mark with two single quotation marks in both sides. Simply stating you require an additional single quote character to print a single quote character. That is if you put two single quote characters Oracle will print one.


2 Answers

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.

like image 197
Paul Sasik Avatar answered Oct 07 '22 08:10

Paul Sasik


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

insert into Person (First, Last) values ('Joe', 'O''Brien') 
like image 30
Justin Niessner Avatar answered Oct 07 '22 06:10

Justin Niessner