Sub topic 6
Collecting records and running DML once
This chapter assumes you know basic Apex syntax, List, Set and Map, and the insert, update and delete statements. It also assumes you know what a trigger is and the difference between before and after events.
Why DML in a loop fails
A transaction can run at most 150 DML statements. A trigger can receive up to 200 records at a time. If the trigger runs one insert or update per record, a full batch uses 200 DML statements and fails with System.LimitException: Too many DML statements: 151.
The limit counts statements, not rows. A single insert of 200 records uses one statement. A transaction can also process at most 10,000 rows through DML, so collecting records does not remove that cap. It only removes the statement count as the bottleneck.
The anti-pattern looks like this:
trigger AccountAfter on Account (after insert) {
for (Account a : Trigger.new) {
// Anti-pattern: one DML statement per record
insert new Task(WhatId = a.Id, Subject = 'Follow up');
}
}With 151 or more accounts in one transaction, this trigger throws a limit exception, and the whole transaction rolls back.
The collect-then-commit pattern
Bulkified DML has three steps:
- Create an empty collection before the loop.
- Add records to the collection inside the loop. Do not run DML here.
- Run one DML statement on the collection after the loop.
trigger AccountAfter on Account (after insert) {
List<Task> tasks = new List<Task>();
for (Account a : Trigger.new) {
tasks.add(new Task(WhatId = a.Id, Subject = 'Follow up'));
}
if (!tasks.isEmpty()) {
insert tasks;
}
}This trigger uses one DML statement whether it receives 1 record or 200.
The isEmpty() check is a good habit. DML on an empty list does not fail, but it still counts as a statement. The check avoids spending one when there is nothing to save.
Updating records you already have
The same pattern applies to updates. Collect the changed records, then run one update.
In a before trigger, you do not need DML at all for the records in Trigger.new. Changes to their fields are saved automatically. Calling update Trigger.new in a before trigger is an error.
In an after trigger, records in Trigger.new are read-only. To change related records, build a list of those records and update it once:
trigger ContactAfter on Contact (after insert) {
Map<Id, Account> accountsToUpdate = new Map<Id, Account>();
for (Contact c : Trigger.new) {
if (c.AccountId != null) {
accountsToUpdate.put(
c.AccountId,
new Account(Id = c.AccountId, Description = 'Has contacts')
);
}
}
if (!accountsToUpdate.isEmpty()) {
update accountsToUpdate.values();
}
}The Map is keyed by Id for a reason. If two new Contacts share one Account, a List would hold that Account twice, and updating a list with the same Id twice throws a Duplicate id in list error. A Map keeps one entry per Id.
Handling partial failures
By default, a DML statement is all or nothing. If one record fails validation, the exception rolls back the whole statement. When you want the valid records saved and the failures reported, use the Database methods with allOrNone set to false:
List<Account> accounts = new List<Account>{
new Account(Name = 'Valid Co'),
new Account() // Name is required, so this one fails
};
List<Database.SaveResult> results = Database.insert(accounts, false);
for (Integer i = 0; i < results.size(); i++) {
if (!results[i].isSuccess()) {
System.debug('Failed: ' + results[i].getErrors()[0].getMessage());
}
}This is still one DML statement. The results list matches the input list by position, so index i in the results refers to index i in accounts.
Common mistakes
| Mistake | Result | Fix |
|---|---|---|
| `insert` or `update` inside a `for` loop | Too many DML statements: 151 | Collect in a List, run DML after the loop |
| Same Id added twice to a List before `update` | Duplicate id in list error | Use a Map keyed by Id |
| `update Trigger.new` in a before trigger | Runtime error | Change fields directly and skip DML |
| DML on an empty List | Wastes one statement | Check `isEmpty()` first |
Exercise
A trigger on Opportunity (after update) loops over Trigger.new and runs update new Account(Id = o.AccountId, Description = 'Updated') for each one. Rewrite the approach so it uses one DML statement and cannot fail on duplicate Ids when several Opportunities share an Account.
Show answer
Create a Map<Id, Account> before the loop. In the loop, skip Opportunities where AccountId is null, and call put(o.AccountId, new Account(Id = o.AccountId, Description = 'Updated')). After the loop, check !accountsToUpdate.isEmpty() and run update accountsToUpdate.values();. The Map holds one Account per Id, so duplicates cannot occur, and there is one DML statement for any batch size.