Are you used to writing Apex like the following for building a dynamic SOQL query in Salesforce? If so, read on for a better way.
     String idInClause = ‘(\”;
     for (Id acctId : accountIds){
    idInClause += acctId + ‘\’,\’’;
     idInClause  = idInClause.substring(0,idInClause.length()-2);
     idInClause += ‘)’;

     String q = ‘select id, name from Account where Id in ‘ + idInClause;

     List<Account> accts = Database.query(q); 

Variable Binding: A Better Way

Using Variable Binding, there’s no more need to build the “IdInClause” anymore. The equivalent Apex code using Variable Binding is:
     Set<Id> accountIds = …
     /* The accountIds variable is directly embedded in the accountQuery string and binded
     against in Database.query
     String accountQuery = ‘select id, name from Account where Id in :accountIds’;
     List<Account> accts = Database.query(accountQuery);
This code is cleaner and takes less script statements to execute. Variable Binding also prevents SOQL injection natively without the use of the escapeSingleQuotes() string function to cleanse string input.


Variable Binding does have limitations, however. It can’t bind directly against functions in the query string like
     String accountQuery = ‘Select id, name from Account where Id in :getAccountids()’;
It also can’t bind against fields on sObjects like
     Account acct = new Account(Id = ‘Some_Acct_Id_Here’);
     String accountQuery = ‘Select id, name from Account where Id = :acct.Id’;
Both cases can still be done by assigning the value(s) to a variable first and then binding against that in the query. ​


Apex Variable Binding in Dynamic SOQL is far superior to building the query up. The code is cleaner, uses less script statements, and secure against SOQL injection. The limitations are easily overcome by assigning the value first to a variable and then binding against that variable in the query.

Happy Coding,