Sub topic 13
Bulk-safe code with collections
This chapter assumes you can write Apex loops and basic SOQL, and that you know List, Set, and Map from the earlier chapters. Here you will use them to keep code within governor limits when a trigger or method receives many records at once.
Why bulk safety matters
Apex runs under governor limits. In one transaction you get at most 100 SOQL queries (synchronous) and 150 DML statements. A trigger can receive up to 200 records at a time. If your code runs a query or DML statement inside a loop, 200 records means 200 queries, and the transaction fails with a limit exception.
The fix is the same each time:
- Collect the keys you need into a Set.
- Query once, outside the loop.
- Put the results in a Map for lookup.
- Loop over the records and read from the Map.
The anti-pattern
This code queries once for every Contact. It works in a test with one record and fails in production.
for (Contact c : contacts) {
Account a = [SELECT Id, Name FROM Account WHERE Id = :c.AccountId];
c.Description = 'Works at ' + a.Name;
update c;
}It has two problems. The query runs inside the loop, and so does the update.
The bulk-safe version
public static void tagContacts(List<Contact> contacts) {
Set<Id> accountIds = new Set<Id>();
for (Contact c : contacts) {
if (c.AccountId != null) {
accountIds.add(c.AccountId);
}
}
Map<Id, Account> accountsById = new Map<Id, Account>(
[SELECT Id, Name FROM Account WHERE Id IN :accountIds]
);
List<Contact> toUpdate = new List<Contact>();
for (Contact c : contacts) {
Account a = accountsById.get(c.AccountId);
if (a != null) {
c.Description = 'Works at ' + a.Name;
toUpdate.add(c);
}
}
update toUpdate;
}Each collection has a job:
| Collection | Role in the pattern |
|---|---|
| Set | Removes duplicate Ids, so the query filters on each Id once |
| Map | Gives constant-time lookup instead of a nested loop or a query |
| List | Holds the records for a single DML statement |
The code makes one query and one update whether it receives 1 record or 200.
Common mistakes
- Querying or running DML inside a loop. Move both outside, as shown above.
- Not checking for null.
Map.getreturns null for a missing key, andc.AccountIdcan be null. Check before you use the result. - Updating an empty list.
updateon an empty List is allowed, but it still counts as a DML statement. CheckisEmpty()first if the list is often empty. - Using a nested loop instead of a Map. Looping over one list inside another does not use extra queries, but it costs CPU time, which is also limited.
Exercise
A trigger receives a List<Opportunity> and needs each Opportunity's Account Name. Which collections do you use, and how many SOQL queries does the code run?
Show answer
Build a Set<Id> of the AccountId values, then run one query with WHERE Id IN :accountIds into a Map<Id, Account>. Loop over the Opportunities and call get on the Map. The code runs one query, no matter how many Opportunities arrive.