Does escapeSingleQuotes escape backslash character too?

From the document it mentions:

If you must use dynamic SOQL, use the escapeSingleQuotes method to sanitize user-supplied input. This method adds the escape character () to all single quotation marks in a string that is passed in from a user. The method ensures that all single quotation marks are treated as enclosing strings, instead of database commands.

However if this only escapes single quote, in theory it does not prevent all kinds of SQL injections. For example,

  1. I can have this as string: test\'@gmail.com.
  2. escapeSingleQuotes will turn this into test\\'@gmail.com
  3. When this is appended to the query:
SELECT Id FROM Contact WHERE Email = 'test\\'@gmail.com'

Backslash character will also need to be escaped to prevent this. If escapeSingleQuotes does escape backslashes too, it may be less confusing if the official document can be updated.


It does escape the backslash before single quote. You should check documentation of escapeSingleQuotes(stringToEscape)

Below is how apex modifies the string - run it in anonymous apex and play-around

String s1 = 'a\'d';
System.assertEquals('a\\\'d', String.escapeSingleQuotes(s1));
System.debug('a\\\'d' == String.escapeSingleQuotes(s1)); //true
System.debug('a\'d'== String.escapeSingleQuotes(s1)); //false

String s2 = 'a\"p';
System.assertEquals('a"p', String.escapeSingleQuotes(s2));

For every single quote and backslash, it will add an extra backslash. Check below in anonymous:

String s1 = 'a\'d';
System.debug('a\\\\\\\'d' == String.escapeSingleQuotes(String.escapeSingleQuotes(s1))); //true
  • Thanks, it's just that the official documentation (including the one you posted) didn't explictly mention escaping backslash. – lulalala Aug 3 '20 at 11:56
  • Your example does not really test for backslashes however: it is just a a'd string. What I want to know would be what happens to escaping 'a\\\'d'. – lulalala Aug 3 '20 at 12:04
  • @lulalala, there is no need for explicitly mentioning it as that is how it is supposed to work or else as you said in question, it will break. I added one more example for your understanding. Hope it will be clear now. – salesforce-sas Aug 3 '20 at 19:54
  • Thanks. It is however important for people implementing similar things in other languages. – lulalala Aug 4 '20 at 1:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.