I'm attempting to create a Ruby on Rails application using Restforce, but the query method doesn't support prepared statements. So I need to escape each input that I put into the query myself. What characters do I need to escape from each input before sending the query to Salesforce? Can I use the Regex.escape function, or do I need to escape other characters as well?

  • 1
    It might just be single quotes that need to be escaped with a backslash. . . – Mike Chale Jul 19 '13 at 13:53

There are a few characters you need to escape when calling SOQL and SOSL, including ', \, _, and % (for some queries only). For more information about escape sequences, see Quoted String Escape Sequences. You might also be required to escape XML-unsafe characters, such as <, >, and " if you're using the SOAP API, or URL-unsafe characters, such as %, @, and so on, when using the REST API. Refer to the specific SOAP/REST library you're using to determine if any additional escapes are required.


I've been doing this in C# for years now with the SOAP API and now I'm carrying it over to the REST API:

public static string SoqlEscape(string plain)
    return plain.Replace("\\", "\\\\").Replace("'", "\\'").Replace("\"", "\\\"");

I run my parameter values through it, like so:

string soql = string.Format("select id from lead where email = '{0}'",

It replaces \ with \\ (has to happen first obviously), ' with \', and " with \". This is not just to prevent malicious injection, but also to accurately represent text in queries. Incredibly rare I'm sure, but Workbench gives very different results for the escaped select subject from case where subject like '%C:\\%' and unescaped select subject from case where subject like '%C:\%' query.


There are some additional character patterns that end up escaping as well, so it is worth being mindful of them. In addition, it sounds like if you use a single backslash without having one of the sequences listed (and not escaping it) the query will break.

enter image description here


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.