Sub topic 8
Writing Handler Methods That Handle 200 Records
This chapter assumes you know basic Apex syntax, DML operations, and governor limits. It also assumes you have a logic-less trigger that calls a handler class which dispatches by Trigger.operationType.
Why 200 Is the Number to Remember
Salesforce passes records to a trigger in chunks of up to 200. A data load, an API call, or a bulk insert can all deliver a full chunk in one execution. Your handler must work the same for 1 record and for 200.
The limits that matter most here apply to the whole transaction, not to each record:
| Limit | Synchronous value |
|---|---|
| SOQL queries issued | 100 |
| DML statements issued | 150 |
A query or DML statement inside a loop uses one unit per record. With 200 records, a loop that queries once per iteration fails at record 101.
The Rule: Collections In, Collections Out
Every handler method should take the whole list or map from the context variables. It should process records in a loop that does no SOQL and no DML. It should then run one query or one DML statement outside the loop.
A Bulk-Safe After Insert
The afterInsert method from the handler shows the shape. It creates one Task per account, adds each to a list, and inserts the list once.
private void afterInsert(List<Account> newAccounts) {
List<Task> followUps = new List<Task>();
for (Account acc : newAccounts) {
followUps.add(new Task(WhatId = acc.Id, Subject = 'Welcome call'));
}
insert followUps; // one DML statement for the whole batch
}For 200 accounts this uses one DML statement. The anti-pattern places insert inside the loop, which would use 200 statements and exceed the limit of 150.
Before Methods Need No DML
In before triggers you change the records in Trigger.new directly. Salesforce saves those changes, so you must not call update on them.
private void beforeUpdate(List<Account> newAccounts, Map<Id, Account> oldMap) {
for (Account acc : newAccounts) {
if (acc.Name != oldMap.get(acc.Id).Name) {
acc.Description = 'Renamed from ' + oldMap.get(acc.Id).Name;
}
}
}Trigger.oldMap is keyed by record Id, so oldMap.get(acc.Id) is a constant-time lookup. This is how you compare old and new values without a query.
Querying Once
Sometimes you need related data. Collect the keys in the loop, query once with IN, then look results up from a map.
private void afterUpdateContacts(List<Account> newAccounts) {
Set<Id> accountIds = new Set<Id>();
for (Account acc : newAccounts) {
accountIds.add(acc.Id);
}
Map<Id, Account> withContacts = new Map<Id, Account>(
[SELECT Id, (SELECT Id FROM Contacts) FROM Account WHERE Id IN :accountIds]
);
for (Account acc : newAccounts) {
Integer contactCount = withContacts.get(acc.Id).Contacts.size();
// Use contactCount here.
}
}The pattern has three steps: gather Ids, query once, read from the map.
Common Errors
- SOQL or DML inside a
forloop. This works in a test with one record and fails in production with a bulk load. Always test with 200 records. - Calling
updateonTrigger.newin a before trigger. Salesforce raises an error, because the records are already part of the save. - Assuming a single record, such as
Trigger.new[0]. This silently ignores the other 199 records. - Unguarded map lookups.
oldMapexists only for update and delete. On insert it isnull, so only use it in methods called for those operations.
Exercise
A handler's afterInsert method contains for (Account acc : newAccounts) { insert new Task(WhatId = acc.Id, Subject = 'Welcome call'); }. A user imports 200 accounts. What happens, and how do you fix it?
Show answer
The loop runs 200 DML statements, which exceeds the limit of 150, so the transaction fails with a "Too many DML statements" error. Build a List<Task> inside the loop with add, then run a single insert on the list after the loop.