Variable Binding in Dynamic SOQL

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.

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:

This code is cleaner and takes less time 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

It also can’t bind against fields on sObjects like

Both cases can still be done by assigning the value(s) to a variable first and then binding against that in the query.

Happy Coding,

Luke