Sub topic 9
Writing changes with one DML statement
This chapter covers the write side of bulkification. The earlier chapters showed how to query once and look up results in a Map. Here you collect every change a trigger needs into a collection and send it to the database with one DML statement. It assumes you can write basic Apex, know insert, update, and Database methods, and have read the chapters on collections and bulk SOQL.
Why one statement matters
A single transaction may run at most 150 DML statements and may process at most 10,000 records across all of them. These limits are separate from each other. A trigger that handles 200 records and calls update once per record uses 200 statements, so it fails on the 151st. The same trigger with one update on a list of 200 uses one statement and 200 rows.
The row limit also counts DML run by other triggers in the same transaction. Fewer statements leave room for them, but the 10,000-row cap still applies however you batch.
The anti-pattern: DML inside a loop
This trigger sets a related account's rating when an opportunity is won. It runs update once per opportunity.
trigger OpportunityTrigger on Opportunity (after insert, after update) {
for (Opportunity opp : Trigger.new) {
if (opp.StageName == 'Closed Won' && opp.AccountId != null) {
Account a = new Account(Id = opp.AccountId, Rating = 'Hot');
update a; // Anti-pattern: one DML statement per record
}
}
}With a data load of 200 won opportunities, this throws System.LimitException: Too many DML statements: 151. A single-record test in the UI will not reveal the problem.
The pattern: build a collection, then run DML once
The fix has three steps:
- Create an empty collection before the loop.
- Add one sObject to it for each change inside the loop.
- After the loop, check that the collection is not empty and run one DML statement on it.
trigger OpportunityTrigger on Opportunity (after insert, after update) {
OpportunityTriggerHandler.markAccountsHot(Trigger.new);
}public with sharing class OpportunityTriggerHandler {
public static void markAccountsHot(List<Opportunity> newOpps) {
Map<Id, Account> accountsToUpdate = new Map<Id, Account>();
for (Opportunity opp : newOpps) {
if (opp.StageName == 'Closed Won' && opp.AccountId != null) {
accountsToUpdate.put(
opp.AccountId,
new Account(Id = opp.AccountId, Rating = 'Hot')
);
}
}
if (!accountsToUpdate.isEmpty()) {
update accountsToUpdate.values();
}
}
}Three details in this code are worth noting.
- Constructing sObjects with only an Id.
new Account(Id = ..., Rating = 'Hot')writes only the fields you set. You do not need to query the account first, and other fields stay unchanged. - The isEmpty guard. An
updateon an empty list does not fail. In current API versions it does not count against the DML statement limit, but the guard makes the intent clear and avoids relying on that behavior. - A Map keyed by Id. Several opportunities in one batch often share an account. The Map keeps one entry per account. The next section explains why that matters.
Duplicate Ids in one list
If you put two sObjects with the same Id in a List and update it, Salesforce rejects the whole statement with System.ListException: Duplicate id in list. A List<Account> built in a loop is easy to get wrong here because 200 opportunities may point to 20 accounts.
Using Map<Id, sObject> as the staging collection avoids this. A second put with the same key replaces the first entry. When the change is the same for every duplicate, as above, this is all you need. When several records contribute to one account, get the existing entry first, change it, and put it back:
Account acc = accountsToUpdate.get(opp.AccountId);
if (acc == null) {
acc = new Account(Id = opp.AccountId);
accountsToUpdate.put(acc.Id, acc);
}
acc.Rating = 'Hot';Otherwise the last record in the loop silently overwrites changes from earlier records.
Before triggers need no DML
The collection pattern applies to records other than the ones that fired the trigger. For the triggering records themselves, the context decides what to do.
| Trigger context | Changing the triggering records | Changing other records |
|---|---|---|
| before insert, before update | Assign to fields on `Trigger.new`. Salesforce saves them. | Use DML on a collection. |
| after insert, after update | `Trigger.new` is read-only. Query the records again and run DML on the copies. | Use DML on a collection. |
A before trigger that calls update on its own Trigger.new records is an error, and it wastes a DML statement even when it is allowed. Field defaults and derived values belong in before triggers. After triggers fit work that needs the record Id or that writes related records, such as the Task creation in the next example.
Choosing between DML statements and Database methods
The insert, update, delete, and undelete statements are all-or-none. If one record in the list fails, the whole operation rolls back and an exception is thrown. The Database class methods take an allOrNone flag and return one result object per record.
| Approach | On a failing record | Returns |
|---|---|---|
| `insert list;` | All records roll back, `DmlException` thrown | Nothing |
| `Database.insert(list, true)` | Same as the statement form | `List<Database.SaveResult>` |
| `Database.insert(list, false)` | Failing records are skipped, others save | `List<Database.SaveResult>` |
Both forms count as one DML statement. The choice is about failure behavior, not limits. Use partial success when records are independent and one bad record should not block the rest. Keep all-or-none when the records only make sense together.
With allOrNone set to false, nothing is thrown, so you must inspect the results. The result list has the same order as the input list, which lets you match each failure back to its source record.
public with sharing class OpportunityTriggerHandler {
public static void createFollowUpTasks(
List<Opportunity> newOpps,
Map<Id, Opportunity> newMap
) {
List<Task> tasks = new List<Task>();
for (Opportunity opp : newOpps) {
if (opp.StageName == 'Closed Won') {
tasks.add(new Task(
Subject = 'Send welcome package',
WhatId = opp.Id,
OwnerId = opp.OwnerId
));
}
}
if (tasks.isEmpty()) {
return;
}
List<Database.SaveResult> results = Database.insert(tasks, false);
for (Integer i = 0; i < results.size(); i++) {
if (!results[i].isSuccess()) {
String message = results[i].getErrors()[0].getMessage();
Opportunity failed = newMap.get(tasks[i].WhatId);
failed.addError('Follow-up task failed: ' + message);
}
}
}
}The trigger calls it with OpportunityTriggerHandler.createFollowUpTasks(Trigger.new, Trigger.newMap);. Calling addError on an opportunity in an after trigger rolls back that opportunity's save. When the trigger runs under a partial-success DML call, such as a Data Loader load, the other records still save.
Mixed sObject types in one list
Apex lets you put different sObject types in a List<SObject> and run DML on it. Salesforce splits such a list into chunks, and every change of type starts a new chunk. A list that alternates between Account and Contact can produce many chunks, and a statement is limited to 10 chunks. For predictable behavior, keep one typed list per object and run one statement for each list. Four related object types then cost four statements, which is still a fixed number.
Order of operations when records depend on each other
Sometimes one DML statement creates the Ids that the next one needs, for example a new Account and its Contacts. Bulkification still applies. Insert all parents in one statement, build a Map from the parent's source record to its new Id, then build the children list and insert it in a second statement. The cost is two statements for any batch size, so a few statements per transaction is expected. A statement count that grows with the batch size is the sign of a problem.
Common mistakes
- Calling DML inside a helper method that is itself called from a loop. The loop is hidden, but the cost is the same.
- Updating the same object type that fired the trigger from an after trigger. This fires the trigger again. The recursion chapter covers how to guard against it.
- Ignoring the
SaveResultlist afterallOrNone = false. Failures then pass without any message.
Exercise
A before update trigger on Contact loops over Trigger.new and, for each contact whose Email changed, calls update c; on that same contact to set Description. The developer says it passes in the UI but fails in a 200-record load. Identify the problems and give the corrected approach.
Show answer
There are two problems. First, the code runs one DML statement per changed contact, so a 200-record load can reach the 150-statement limit. Second, a before trigger does not need DML on its own records. Salesforce saves field changes made to Trigger.new records after the trigger finishes. The fix is to delete the update c; line and assign c.Description = ... directly in the loop. If the work were on related records, such as updating parent Accounts, the trigger would instead add them to a Map<Id, Account> and run one update map.values(); after the loop.
Exercise
An after update trigger on Opportunity builds a List<Account> and adds one Account for each won opportunity. In testing with 50 opportunities that belong to 5 accounts, the update fails. What is the error, and how do you fix it?
Show answer
The list contains several Account entries with the same Id, so the update throws System.ListException: Duplicate id in list. Change the staging collection to Map<Id, Account> keyed by AccountId, put one entry for each account, and run update accountsMap.values();. If several opportunities contribute different changes to the same account, get the existing entry from the Map and modify it instead of creating a new one.