How do I escape an apostrophe (single quote) in my SOQL statement?
Tuesday, May 22, 2012 at 2:04PM This is one of those things you don't need to do all that often but when you do, you can't seem to figure out how to make it work. I ran into this earlier today. I had a SOQL statement that kept returing a "MALFORMED_QUERY".
I started to debug it and realized that it was happening when I was looking for accounts where the name had an apostrophe (single quote) in it.
A quick example would be something like:
L'Oreal
If you want to find all the accounts where the name starts with L'Oreal you would need to escape the apostrophe (single quote). In the Force.com Explorer, all you need to do it put a \ before the apostrophe like so:
Select Id, Name, (Select Id, Name From Contacts) From Account where name like '%L\'Oreal%'
Now, if you are building the SOQL dynamically and you are not sure when/where the single quote could appear, Salesforce has though of it. There is a nice and handy escapeSingleQuotes string method. It takes a string as an argument and returns a string with all the single quote instances escaped. This saved a lot time and guess work.
soql escape character 
