Salesforce SOQL Query – Dynamically Pass Bind Variables

Article on how to use bind-variables for Salesforce SOQL and SOSL in APEX – Database.queryWithBinds, Database.getQueryLocatorWithBinds, Database.countQueryWithBinds

Dynamically Pass Bind Variables to a SOQL Query

We are mostly using some Variables when we writing SOQL and SOSL queries in Apex. Using Variables in SOQL and SOSL Called Bind Variables.
The bind variables in the query are resolved from a Map parameter directly with a key instead of from Apex code variables with the new

Database.queryWithBinds , Database.getQueryLocatorWithBinds, and Database.countQueryWithBinds

methods. The variables are not required to be in scope when the query is run as a result.
The advantage of below methods is we don’t need to create a separate variable for the usage of SOQL query, where as we can directly define the variable with in the map.

Example of Database.queryWithBinds 

Return Type: String 
Map<String, Object> accBinds = new Map<String, Object>{'accName' => 'United Oil & Gas, UK'}; 
 
List<Account> accts = Database.queryWithBinds('SELECT Id FROM Account WHERE Name = :accName',accBinds, AccessLevel.USER_MODE);

Example of Database.countQueryWithBinds 

Return Type: Integer 

Return the number of records that a dynamic SOQL query would return when executed. 

Map<String, Object> accBinds = new Map<String, Object>{'accName' => 'United Oil & Gas, UK'}; 

Integer acctCount = Database.countQueryWithBinds('SELECT count() FROM Account WHERE Name = :accName', accBinds, AccessLevel.USER_MODE);