can anyone tell me what this query do? and what does this character \' do?

String type = 'prospect';

String query;

query = 'SELECT Id, Account_ID__c ,ProspectHello__c FROM Account where type=' + '\'' + type + '\'' + ' and Account_ID__c =' + '\'' +  testID + '\'' + ' LIMIT 1';

1 Answer 1


It's an escape character. '\'' is how you include a literal single quote inside a string in Apex - any string, not just a query.

Your snippet is constructing a dynamic SOQL query to locate a single Account with a given Id (testId) and the Type 'prospect'.

Note that in many cases it is superior to use Apex binding rather than to construct queries as strings. Apex binding allows the compiler to check the validity of the query at compile time, rather than run time, and ensures that all data conversion is handled for you. For more, see Using Apex Variables in SOQL and SOSL Queries

Adrian rightly enjoins me to mention injection vulnerabilities. Constructing a SOQL query dynamically, using any values that stem directly or indirectly from user input, runs the risk of a malicious user providing a carefully constructed input value that, when included in a dynamic SOQL query like you do here, "breaks out" of the bounds of an enclosing quote pair '' by including its own literal ' - and additional material that would change the behavior of your query, like pulling out additional fields to which the user wouldn't otherwise have access or other clever attacks. (There are a couple of other variants, but that's the most well-known - link for more below).

You can guard against injection attacks of that nature by always using String.escapeSingleQuotes(inputString) to sanitize any string used in dynamic SOQL that derives from user input. For more on that and a few other wrinkles on injection attacks, see the excellent Trailhead unit (the whole advanced security sequence of modules is well worth the time, too!)

... overall, it's easier and safer to use binding with non-dynamic queries, unless your use case truly requires fully dynamic SOQL.

  • 3
    This answer could use a mention of injection vulnerabilities.
    – Adrian Larson
    Commented Jun 14, 2018 at 19:28

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .