Get Hands-on with Bind Variables in a SOQL Query
Learning Objective
After completing this unit, you’ll be able to:
- Dynamically Pass Bind Variables to a SOQL Query.
Dynamically Pass Bind Variables to a SOQL Query
With the new Database.queryWithBinds
, Database.getQueryLocatorWithBinds
, and Database.countQueryWithBinds
methods, the bind variables in the query are resolved from a Map parameter directly with a key rather than from Apex code variables.
This change applies to Lightning Experience and Salesforce Classic in Enterprise, Performance, Unlimited, and Developer editions.
In this example, the SOQL query uses a bind variable for an Account name. Its value (Acme Inc.
) is passed into the method using the nameBind
Map. The accountName
variable isn't (and doesn’t have to be) in scope when the query is executed within the method.
public static List<Account> simpleBindingSoqlQuery(Map<String, Object> bindParams) { String queryString = 'SELECT Id, Name ' + 'FROM Account ' + 'WHERE name = :name'; return Database.queryWithBinds( queryString, bindParams, AccessLevel.USER_MODE ); } String accountName = 'Acme Inc.'; Map<String, Object> nameBind = new Map<String, Object>{'name' => accountName}; List<Account> accounts = simpleBindingSoqlQuery(nameBind); System.debug(accounts);
Get Ready for the Hands-on Challenge
In the hands-on challenge below, you’ll have an opportunity to work with bind variables.
Create a new Trailhead Playground now to follow along and try out the steps in this module. Scroll to the bottom of this page, click the playground name, and then select Create Playground. It typically takes 3–4 minutes for Salesforce to create your Trailhead Playground.
Launch the org you’ll use for the hands-on challenge, then do the following prework.
- Create an Apex class
- Name:
QueryContact
- Replace the contents of the
QueryContact
class with the following code:
- Name:
public class QueryContact { public static Id getContactID(String lastName, String title) { try { Contact myContact = Database.query( 'SELECT ID FROM Contact WHERE lastName = :lastName AND title = :title LIMIT 1' ); return myContact.Id; } catch (Exception ex) { return null; } } public static Id getContactIDWithBinds(Map<String, Object> bindVars) { //do not modify any code above this line //implement the logic that will use bindVars to retrieve the contact's ID return null; } }