« Salesforce ID Clipper | Main | Bring on the Java Developers! »

Escape apostrophe in SOQL statement

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:


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 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.



PrintView Printer Friendly Version

EmailEmail Article to Friend

Reader Comments

There are no comments for this journal entry. To create a new comment, use the form below.

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
All HTML will be escaped. Hyperlinks will be created for URLs automatically.