SQL to Query text in access with an apostrophe in it

Kevin picture Kevin · Jul 20, 2011 · Viewed 117.7k times · Source

Please help me with this because I cannot seem to get it right

I am trying to query a name(Daniel O'Neal) in column names tblStudents in an access database however access reports a syntax error with the statement:

Select * from tblStudents where name like 'Daniel O'Neal'

because of the apostrophe in the name.

How do I overcome this.

Thank you in advance

Answer

Alex K. picture Alex K. · Jul 20, 2011

You escape ' by doubling it, so:

Select * from tblStudents where name like 'Daniel O''Neal' 

Note that if you're accepting "Daniel O'Neal" from user input, the broken quotation is a serious security issue. You should always sanitize the string or use parametrized queries.