Sub topic 9
Writing changes with one DML statement
This chapter assumes you know basic Apex, SOQL, and DML statements such as insert and update. It also assumes you know that a trigger receives up to 200 records per invocation, and that one transaction shares a single set of governor limits.
Why DML belongs outside the loop
A synchronous transaction can run at most 150 DML statements and process at most 10,000 DML rows. A DML statement counts once no matter how many records it carries. Inserting 200 records in one statement uses 1 statement. Inserting them one at a time uses 200 and fails with a limit exception.
The following trigger has this problem:
trigger OpportunityTrigger on Opportunity (after update) {
for (Opportunity opp : Trigger.new) {
if (opp.StageName == 'Closed Won') {
// Anti-pattern: one DML statement per record
insert new Task(
Subject = 'Send welcome package',
WhatId = opp.Id,
OwnerId = opp.OwnerId
);
}
}
}With 151 or more won opportunities in one batch, this throws System.LimitException: Too many DML statements: 151.
The pattern: collect, then write once
Build a collection inside the loop. Run the DML statement after the loop ends.
trigger OpportunityTrigger on Opportunity (after update) {
List<Task> tasks = new List<Task>();
for (Opportunity opp : Trigger.new) {
if (opp.StageName == 'Closed Won') {
tasks.add(new Task(
Subject = 'Send welcome package',
WhatId = opp.Id,
OwnerId = opp.OwnerId
));
}
}
if (!tasks.isEmpty()) {
insert tasks;
}
}The isEmpty() check is optional, because DML on an empty list does nothing. Many teams keep the check to make the intent clear.
Updating related records
Updating parent records follows the same pattern. Several child records can point to the same parent, and a List that holds the same record Id twice makes update fail with a duplicate Id error. Use a Map<Id, SObject> keyed by Id, and update its values.
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')
);
}
}
update accountsToUpdate.values();Repeated put calls with the same key overwrite each other, so each Account appears once.
Common mistakes
- Calling
insertorupdateinside a nested loop or inside a helper method that the loop calls. - Putting the same record Id in a List more than once.
- Updating Trigger.new records in an after trigger. Those records are read-only there.
- Ignoring the 10,000-row limit when one batch of 200 records creates many child records each.
Exercise
A before update trigger loops over Trigger.new and sets c.Description on each Contact. A teammate adds "update c;" inside the loop. Why is this wrong, and what should replace it?
Show answer
Records in Trigger.new in a before trigger are saved automatically, so no DML is needed for them. Calling update on them inside the loop also uses one DML statement per record and risks the 150-statement limit. Remove the update statement and keep only the field assignment. If other objects need changes, add them to a collection and run one DML statement after the loop.