Sub topic 8
Querying once and looking up results in a Map
This chapter assumes you know basic Apex syntax, SOQL, and how a trigger receives a list of records in Trigger.new. It builds on collecting IDs in a Set. Here you use those IDs in one query and read the results from a Map.
The problem with one query per record
A trigger can receive up to 200 records in one invocation. A synchronous transaction allows 100 SOQL queries. If the trigger runs one query for each record, a batch of 101 or more records fails with a limit exception.
trigger ContactTrigger on Contact (before insert) {
for (Contact c : Trigger.new) {
// Anti-pattern: one SOQL query per record
Account a = [SELECT Id, Industry FROM Account WHERE Id = :c.AccountId];
if (a.Industry == 'Banking') {
c.Description = 'Banking contact';
}
}
}This code has a second bug. When AccountId is null, the query returns no rows, and assigning an empty result to a single Account throws a QueryException.
The three-step pattern
Bulk querying always follows the same steps:
- Loop over
Trigger.newand collect the IDs you need into a Set. - Run one query with an
INclause, and store the results in a Map. - Loop over
Trigger.newagain and read each record's related data from the Map.
The bulkified trigger
trigger ContactTrigger on Contact (before insert, before update) {
Set<Id> accountIds = new Set<Id>();
for (Contact c : Trigger.new) {
if (c.AccountId != null) {
accountIds.add(c.AccountId);
}
}
Map<Id, Account> accountsById = new Map<Id, Account>(
[SELECT Id, Industry FROM Account WHERE Id IN :accountIds]
);
for (Contact c : Trigger.new) {
Account a = accountsById.get(c.AccountId);
if (a != null && a.Industry == 'Banking') {
c.Description = 'Banking contact';
}
}
}The trigger uses one query whether it receives 1 record or 200.
Why it works
- A Set removes duplicates. If 150 contacts share one account, the Set holds that ID once, so the query returns one row for it.
IN :accountIdsbinds the whole Set. SOQL accepts a collection in a bind variable, so one query fetches every account.- The Map constructor takes a list of sObjects.
new Map<Id, Account>(queryResult)uses each record'sIdas the key. You don't write a loop to fill it. getreturns null for a missing key. A contact with no account, or an account you can't read, gives null. Check for null before you use the result.
Common mistakes
- Putting the null check on
AccountIdin the first loop but not on the Map result in the second. Keep both. - Querying with an empty Set. This is legal and returns no rows, but it still counts as a query. Skip the query with
if (!accountIds.isEmpty())when it matters. - Selecting fewer fields than you read. Reading a field you did not query throws a
SObjectException. Add every field you use to theSELECTlist. - Using the Map for a different key. When you need to look up by something other than
Id, such as an email address, build the Map yourself with a loop andput.
Exercise
A trigger on Case collects ContactId values into a Set, queries Contact with WHERE Id IN :contactIds, and stores the result in Map<Id, Contact> contactsById. A case has no contact. What does contactsById.get(c.ContactId) return for that case, and what should the code do before using it?
Show answer
It returns null, because the Map has no entry for a null key. The code should check that the result is not null before it reads any field from it. Without the check, accessing a field on the null value throws a NullPointerException.