Sub topic 8
Querying once and looking up results in a Map
This chapter assumes you can read Apex classes and triggers, write basic SOQL with bind variables, and use the Trigger.new and Trigger.oldMap context variables. It also assumes you know the limit of 100 SOQL queries per synchronous transaction. The goal is to replace a query per record with one query per trigger invocation, and to find each record's related data in memory.
The pattern in four steps
Every bulk lookup follows the same shape:
- Loop over the trigger records and collect the lookup keys into a
Set. - Run one SOQL query that filters with
IN :set. - Store the results in a
Mapso each one can be found by key. - Loop over the trigger records again and read from the Map.
The loop never runs a query. A batch of 1 record and a batch of 200 records both use exactly one query.
Querying by ID with a Map
The anti-pattern runs a query inside the loop. Here is the corrected version:
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';
}
}
}Three details matter here.
- The
Map<Id, Account>constructor accepts a list of sObjects and uses each record'sIdas the key. You do not need a loop to fill it. accountsById.get(null)returnsnulland does not throw. A contact without an account therefore falls through thea != nullcheck. The null check when building the Set keepsnullout of the bind variable.- Assigning to
c.Descriptionworks because this is abeforetrigger. The records inTrigger.neware editable and are saved without a DML statement.
Always null-check the result of get. A key can be missing because the record was deleted, because the user cannot see it under sharing rules, or because the query filtered it out.
Skipping the query when there is nothing to look up
If every contact in the batch has no account, accountIds is empty. SOQL with an empty IN set returns no rows, but it still counts against the 100-query limit. Guard the query when a trigger runs on many kinds of data:
Map<Id, Account> accountsById = new Map<Id, Account>();
if (!accountIds.isEmpty()) {
accountsById = new Map<Id, Account>(
[SELECT Id, Industry FROM Account WHERE Id IN :accountIds]
);
}This costs one if and saves a query in the cases where the batch has no keys.
Maps keyed by something other than Id
The Map constructor only keys by Id. For any other key, such as a name, an external ID, or a parent ID, fill the Map in a loop. The following trigger matches new leads to existing accounts by company name:
trigger LeadTrigger on Lead (before insert) {
Set<String> names = new Set<String>();
for (Lead l : Trigger.new) {
if (String.isNotBlank(l.Company)) {
names.add(l.Company.toLowerCase());
}
}
Map<String, Account> accountsByName = new Map<String, Account>();
if (!names.isEmpty()) {
for (Account a : [SELECT Id, Name FROM Account WHERE Name IN :names]) {
accountsByName.put(a.Name.toLowerCase(), a);
}
}
for (Lead l : Trigger.new) {
if (String.isBlank(l.Company)) {
continue;
}
Account match = accountsByName.get(l.Company.toLowerCase());
if (match != null) {
l.Description = 'Existing account: ' + match.Id;
}
}
}If two accounts share a name, the second put overwrites the first. That is acceptable only if you do not care which one wins. If it matters, add an ORDER BY to make the choice deterministic, or store a List<Account> per key.
Grouping many children under one parent
Some lookups return several records per key. A single key then maps to a List, and you build the list as you iterate:
public with sharing class ContactLookup {
public static Map<Id, List<Contact>> groupByAccount(Set<Id> accountIds) {
Map<Id, List<Contact>> result = new Map<Id, List<Contact>>();
if (accountIds.isEmpty()) {
return result;
}
for (Contact c : [
SELECT Id, LastName, AccountId
FROM Contact
WHERE AccountId IN :accountIds
]) {
if (!result.containsKey(c.AccountId)) {
result.put(c.AccountId, new List<Contact>());
}
result.get(c.AccountId).add(c);
}
return result;
}
}When you read from this Map, a parent with no children has no entry. Use result.get(accountId) and check for null, or call containsKey first.
A parent-to-child subquery is an alternative that counts as one query and needs no grouping code:
Map<Id, Account> accountsWithContacts = new Map<Id, Account>([
SELECT Id, Name, (SELECT Id, Email FROM Contacts)
FROM Account
WHERE Id IN :accountIds
]);
for (Id accId : accountIds) {
Account a = accountsWithContacts.get(accId);
if (a != null) {
Integer contactCount = a.Contacts.size();
}
}The subquery form is shorter. The explicit grouping form lets you filter or reuse the Map across several methods without repeating the query.
Edge cases and limits
- Total rows. A synchronous transaction can retrieve at most 50,000 rows across all SOQL queries. One query does not avoid this limit. A trigger that loads every contact of 200 large accounts can exceed it. Select only the fields you need, and add
WHEREconditions that narrow the result. Trigger.newMapand keys. Inafter insert,after update, andbefore update,Trigger.newMap.keySet()gives you the record IDs directly. Inbefore insertthe records have no IDs yet, soTrigger.newMapisnull. Collect lookup keys from fields on the records instead.- Stale results. A Map is a snapshot from the moment of the query. If your code or another trigger changes the queried records later in the same transaction, the Map does not update. Re-query only when you need the new values, and do so once.
- Shared helpers. A handler that needs the same accounts in two methods should query once and pass the Map into both. Two methods that each query the same set cost two queries per invocation.
- Cascading triggers. If an
aftertrigger updates records and fires other triggers in the same transaction, the SOQL count is shared across all of them. Plan for a small budget per trigger, not the whole 100.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Query inside the `for` loop over `Trigger.new` | Fails with "Too many SOQL queries: 101" at 101 records | Collect keys, query once |
| Adding `null` to the key Set | Wasted work, and sometimes confusing results | Check for `null` before `add` |
| Calling `map.get(key).Field` with no null check | `NullPointerException` when the key is missing | Assign to a variable and test it |
| Mixed-case String keys | Silent misses on lookup | Lowercase both sides |
| Querying fields you never read | Larger heap use and slower queries | Select only what the logic uses |
Exercise
A before insert trigger on Case copies the Region__c value from the related Account onto each Case. Write the three pieces the trigger needs before the final loop: the Set, the query, and the Map. What happens to a Case with no AccountId?
Show answer
Build a Set<Id> accountIds by looping over Trigger.new and adding c.AccountId when it is not null. Then run Map<Id, Account> accountsById = new Map<Id, Account>([SELECT Id, Region__c FROM Account WHERE Id IN :accountIds]);, guarded by if (!accountIds.isEmpty()) if you want to skip the query for empty batches. In the final loop, read Account a = accountsById.get(c.AccountId); and set c.Region__c = a.Region__c only when a != null. A Case with no AccountId gets get(null), which returns null, so the Case is skipped and no error is thrown.
Exercise
A trigger builds Map<String, Account> keyed by Name, but lookups for Acme Corp sometimes fail even though the account exists as ACME CORP. Explain the cause and the fix.
Show answer
SOQL matches names case-insensitively, so the query returns the account. The Apex Map is case-sensitive, so get('Acme Corp') does not find the key ACME CORP. The fix is to lowercase the key when calling put and again when calling get, and to lowercase the values placed in the Set.