Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I deal with quotes ' in SQL [duplicate]

Tags:

sql

oracle

I have a database with names in it such as John Doe etc. Unfortunately some of these names contain quotes like Keiran O'Keefe. Now when I try and search for such names as follows:

SELECT * FROM PEOPLE WHERE SURNAME='O'Keefe' 

I (understandably) get an error.

How do I prevent this error from occurring. I am using Oracle and PLSQL.

like image 901
Calanus Avatar asked Aug 27 '08 08:08

Calanus


People also ask

How do you handle double quotes in SQL query?

Use two single quotes to escape them in the sql statement. The double quotes should not be a problem: SELECT 'How is my son''s school helping him learn?

How does SQL Server handle double quotes?

If you need to use the double quote inside the string, you can use the backslash character. Notice how the backslash in the second line is used to escape the double quote characters. And the single quote can be used without a backslash.

How do you handle quotes in SQL?

Use Two Single Quotes For Every One Quote To Display Vendors: Oracle, SQL Server, MySQL, PostgreSQL. The simplest method to escape single quotes in SQL is to use two single quotes. For example, if you wanted to show the value O'Reilly, you would use two quotes in the middle instead of one.

How do you change double quotes into single quotes in SQL?

Backspace over the double quotes and then type a single quote.


2 Answers

The escape character is ', so you would need to replace the quote with two quotes.

For example,

SELECT * FROM PEOPLE WHERE SURNAME='O'Keefe'

becomes

SELECT * FROM PEOPLE WHERE SURNAME='O''Keefe'

That said, it's probably incorrect to do this yourself. Your language may have a function to escape strings for use in SQL, but an even better option is to use parameters. Usually this works as follows.

Your SQL command would be :

SELECT * FROM PEOPLE WHERE SURNAME=?

Then, when you execute it, you pass in "O'Keefe" as a parameter.

Because the SQL is parsed before the parameter value is set, there's no way for the parameter value to alter the structure of the SQL (and it's even a little faster if you want to run the same statement several times with different parameters).

I should also point out that, while your example just causes an error, you open youself up to a lot of other problems by not escaping strings appropriately. See http://en.wikipedia.org/wiki/SQL_injection for a good starting point or the following classic xkcd comic.

alt text

like image 187
Matt Sheppard Avatar answered Oct 12 '22 18:10

Matt Sheppard


Oracle 10 solution is

SELECT * FROM PEOPLE WHERE SURNAME=q'{O'Keefe}'
like image 28
Laurent Schneider Avatar answered Oct 12 '22 18:10

Laurent Schneider