Skip to main content
Build the future with Agentforce at TDX in San Francisco or on Salesforce+ on March 5–6. Register now.

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. 

Note

Yes, we really mean a brand-new Trailhead playground! If you use an existing org or playground, you can run into problems completing the challenges.

Launch the org you’ll use for the hands-on challenge, then do the following prework.

  1. Create an Apex class
    1. Name: QueryContact
    2. Replace the contents of the QueryContact class with the following code:
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;
    }
}

Resources

Salesforce 도움말에서 Trailhead 피드백을 공유하세요.

Trailhead에 관한 여러분의 의견에 귀 기울이겠습니다. 이제 Salesforce 도움말 사이트에서 언제든지 새로운 피드백 양식을 작성할 수 있습니다.

자세히 알아보기 의견 공유하기