Sub topic 13
Bulk-safe code with collections
Prerequisites
This chapter assumes you can read Apex triggers and classes, and that you know how List, Set, and Map work, including Map<Id, SObject> built from a SOQL result and keySet(). It also assumes you can write a basic SOQL WHERE ... IN :bindVariable query.
Why code must be bulk-safe
Apex runs under governor limits, which are per-transaction caps enforced by the platform. A transaction is one unit of work, such as a trigger firing or a Queueable job running. Synchronous transactions have these limits:
| Resource | Limit per transaction |
|---|---|
| SOQL queries issued | 100 |
| Rows returned by SOQL | 50,000 |
| DML statements | 150 |
| Rows processed by DML | 10,000 |
| Heap size | 6 MB |
A trigger receives up to 200 records at a time. A data load, an API call, or a flow can all deliver that many. Code written for one record, such as a query inside a loop, uses 200 queries when 200 records arrive. The 101st query throws a System.LimitException, which cannot be caught, and the whole transaction rolls back.
Bulk-safe code uses the same number of queries and DML statements whether it handles 1 record or 200. Collections make that possible.
The working model
Every bulk-safe method follows four steps:
- Loop once to collect keys, usually Ids, into a Set.
- Query once, outside any loop, with
IN :set. - Put the results in a Map (for lookups) or a Map of Lists (for children).
- Loop again to read from the Map, change records, and add them to a List. Run one DML statement on that List.
Each collection type has one job in this model. The Set removes duplicate Ids so the query filter stays small. The Map replaces a per-record query with an in-memory lookup. The List batches the records for DML.
The anti-pattern
This trigger looks reasonable and fails on the 101st contact:
trigger ContactBeforeInsertBad on Contact (before insert) {
for (Contact c : Trigger.new) {
// One query per record. Also throws QueryException if no row matches.
Account a = [SELECT Name FROM Account WHERE Id = :c.AccountId];
c.Description = 'Works at ' + a.Name;
}
}There are two bugs here. The query is inside the loop, and a single-row query assignment throws a QueryException when it finds zero rows. A contact with no account triggers that exception.
Lookup with a Set and a Map
The bulk-safe version issues one query regardless of batch size:
trigger ContactBeforeInsert on Contact (before insert) {
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, Name FROM Account WHERE Id IN :accountIds]
);
for (Contact c : Trigger.new) {
Account a = accountsById.get(c.AccountId);
if (a != null) {
c.Description = 'Works at ' + a.Name;
}
}
}Three details matter here:
- The null check before
accountIds.addkeeps null out of the Set. A null in anINlist is harmless but wasteful. accountsById.get(c.AccountId)returns null for a missing key, including a null key. Thea != nullcheck handles contacts with no account and contacts whose account is not visible to the user.- This is a before trigger, so changing
c.Descriptionneeds no DML. The platform saves the changes.
Children with a Map of Lists
When the query returns child records, several rows share one parent key. A Map of Lists holds them. The next class gives every contact of an account a description containing the account's contact count:
public class ContactDescriptionService {
public static void setTeamSize(List<Account> accounts) {
Set<Id> accountIds = new Map<Id, Account>(accounts).keySet();
Map<Id, List<Contact>> contactsByAccount = new Map<Id, List<Contact>>();
for (Contact c : [
SELECT Id, AccountId
FROM Contact
WHERE AccountId IN :accountIds
]) {
if (!contactsByAccount.containsKey(c.AccountId)) {
contactsByAccount.put(c.AccountId, new List<Contact>());
}
contactsByAccount.get(c.AccountId).add(c);
}
List<Contact> toUpdate = new List<Contact>();
for (Account a : accounts) {
List<Contact> team = contactsByAccount.get(a.Id);
if (team == null) {
continue;
}
for (Contact c : team) {
c.Description = 'Team size: ' + team.size();
toUpdate.add(c);
}
}
if (!toUpdate.isEmpty()) {
update toUpdate;
}
}
}The class uses one query and at most one DML statement. The nested loops are fine. They run in memory and count against CPU time, not against the query or DML limits.
Calling it from an after update trigger looks like this:
trigger AccountAfterUpdate on Account (after update) {
ContactDescriptionService.setTeamSize(Trigger.new);
}The if (!toUpdate.isEmpty()) guard is optional. Running update on an empty list works, but it still counts as a DML statement against the limit of 150.
Edge cases
Duplicate records in a DML list
If the same record Id appears twice in a List passed to update, Apex throws System.ListException: Duplicate id in list. In the example above, accounts comes from Trigger.new, so each Id appears once. If a caller passed the same account twice, a contact would be added to toUpdate twice and the update would fail.
When duplicates are possible, collect changes in a Map<Id, Contact> instead of a List. Putting the same Id twice overwrites the entry, then update map.values() runs once:
Map<Id, Contact> changes = new Map<Id, Contact>();
for (Contact c : team) {
c.Description = 'Team size: ' + team.size();
changes.put(c.Id, c);
}
update changes.values();An empty Set in a query
WHERE AccountId IN :accountIds with an empty Set is valid and returns no rows. The query still counts against the 100-query limit. If a method often has nothing to look up, return early with if (accountIds.isEmpty()) return;.
Very large result sets
The 50,000-row cap applies to all queries in the transaction together. If a query might return more rows than the heap or row limit allows, a for loop over the query directly, as in the Map of Lists example, uses less heap than storing the result in a List first. SOQL for loops retrieve rows in chunks of 200. For truly large volumes, move the work to Batch Apex.
Order of results
A Set and a Map do not guarantee iteration order. If your logic depends on order, such as "first contact created", add ORDER BY to the query and keep the results in a List.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `Too many SOQL queries: 101` | Query inside a loop, or a method that queries and is called once per record | Pass collections into the method and query once |
| `Too many DML statements: 151` | `insert`, `update`, or `delete` inside a loop | Add records to a List and run DML after the loop |
| `NullPointerException` on `map.get(key).field` | Key missing from the Map | Assign to a variable and check for null first |
| `QueryException: List has no rows for assignment` | Single-row query with no match | Query into a List and check `isEmpty()` |
| `Duplicate id in list` | Same Id twice in the DML List | Collect changes in a `Map<Id, SObject>` |
| Update does nothing in a before trigger | Changed a queried copy instead of the `Trigger.new` record | Modify the `Trigger.new` record directly |
Checklist
- Is there any SOQL or DML inside a
fororwhileloop? Move it out. - Is every query filtered with
IN :setand not a single Id? - Does every
map.get(...)result get a null check? - Is DML run once on a List or a Map's
values(), with no duplicate Ids? - Have you tested with 200 records, not only 1?
Exercise
This method is called from a trigger with up to 200 Opportunity records. Rewrite it so it uses one SOQL query regardless of batch size, and say what happens when an Opportunity has no Account. public static void copyIndustry(List<Opportunity> opps) { for (Opportunity o : opps) { Account a = [SELECT Industry FROM Account WHERE Id = :o.AccountId]; o.Description = a.Industry; } }
Show answer
Collect the AccountIds into a Set (skipping nulls), query once into a Map, then look up each account: public static void copyIndustry(List<Opportunity> opps) { Set<Id> accountIds = new Set<Id>(); for (Opportunity o : opps) { if (o.AccountId != null) { accountIds.add(o.AccountId); } } Map<Id, Account> accountsById = new Map<Id, Account>( [SELECT Id, Industry FROM Account WHERE Id IN :accountIds] ); for (Opportunity o : opps) { Account a = accountsById.get(o.AccountId); if (a != null) { o.Description = a.Industry; } } } The original throws a QueryException for an Opportunity with no Account, because the single-row query finds no rows. In the rewrite, such an Opportunity gets a null from the Map, the null check skips it, and no exception occurs. The rewrite assumes a before trigger, where no DML is needed to save the change.