Sub topic 6
Collecting records and running DML once
DML statements (insert, update, delete, undelete, upsert, merge) are the second most common cause of governor limit failures, after SOQL queries in loops. This chapter shows how to find DML inside loops and replace it with a collect-then-write pattern.
This chapter assumes you know Apex loops and collections, basic DML syntax, and the difference between before and after triggers. It builds on the previous chapters about per-transaction limits and moving SOQL out of loops.
What the DML limits count
Two separate limits apply to DML in one transaction:
| Limit | Synchronous and asynchronous value | What it counts |
|---|---|---|
| DML statements | 150 | Each executed DML statement or `Database.*` DML method call |
| DML rows | 10,000 | Each record processed by those statements |
Check the current numbers in the Apex Developer Guide, "Execution Governors and Limits", because Salesforce can change them.
The two limits behave differently. The statement limit punishes how you write the code: a statement that sits in a loop runs once per iteration. The row limit punishes how much data you touch, however well the code is written. One update on a list of 200 records uses 1 statement and 200 rows. Bulkifying reduces statements. It does not reduce rows.
The limits apply to the whole transaction, not to each trigger or class. If your trigger fires after a flow, a workflow update, or another trigger, they all draw from the same budget.
The anti-pattern: DML inside a loop
This trigger inserts one Task per Account, with a separate insert for each:
trigger AccountAfterBad 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 1 to 20 Accounts it works, and a developer testing in the UI would never see a problem. Data Loader, an API client, or a bulk import can send 200 Accounts in one chunk. Statement 151 throws System.LimitException: Too many DML statements: 151. That exception cannot be caught, so the whole transaction rolls back.
The fix: collect, then write once
The pattern has three steps:
- Declare a collection before the loop.
- Add records to it inside the loop.
- 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 uses one DML statement whether the batch holds 1 record or 200. The isEmpty() check keeps the intent clear and avoids running DML when there is nothing to save.
Choosing the right collection
Which collection you use depends on what you are saving.
- List. Use it for new records or for records you already hold, such as
Trigger.newin a before trigger or query results. - Map keyed by Id. Use it when several source records can map to the same target record, so you save each target once.
- Set. Use it to remember Ids you have already handled, or to collect Ids for a query before the DML step.
Duplicate Ids in an update list
Updating a parent from its children is a common case. Suppose 200 new Contacts belong to only 3 Accounts. If you add one Account to a list for every Contact, the list holds many entries with the same Id, and update fails with System.ListException: Duplicate id in list.
A Map avoids this. put with an existing key replaces the earlier entry, so each Account appears 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();
}
}new Account(Id = ..., Description = ...) creates a lightweight record that carries only the Id and the field you want to change. Fields you leave unset are not touched. This also avoids a query when you only need to write.
Because later put calls overwrite earlier ones, the last Contact for an Account wins. If several children must each contribute to the same parent, fetch the existing entry from the Map and modify it instead of replacing it:
trigger OpportunityAfter on Opportunity (after insert) {
Map<Id, Account> accountsToUpdate = new Map<Id, Account>();
for (Opportunity o : Trigger.new) {
if (o.AccountId == null) {
continue;
}
Account a = accountsToUpdate.get(o.AccountId);
if (a == null) {
a = new Account(Id = o.AccountId, NumberOfEmployees = 0);
accountsToUpdate.put(o.AccountId, a);
}
a.NumberOfEmployees += 1;
}
if (!accountsToUpdate.isEmpty()) {
update accountsToUpdate.values();
}
}This example only demonstrates the get-or-create pattern. It does not model a real business rule, because it overwrites the existing value rather than adding to it.
When you do not need DML at all
In a before trigger, changes you make to records in Trigger.new are saved automatically. Calling update Trigger.new there is unnecessary and wrong. Before-trigger DML on the same records is not allowed, and it would waste a statement even where it was.
In an after trigger, the records in Trigger.new are read-only. If you need to change the triggering records themselves, query them again or build new SObject instances with the same Ids, and update those. In many cases a before trigger is the better place for the change.
| Trigger event | Changing the triggering records | Changing other records |
|---|---|---|
| before insert / before update | Assign fields directly, with no DML | Collect and run DML once |
| after insert / after update | Not allowed on `Trigger.new`; requery or create new instances | Collect and run DML once |
Handling partial failures
By default, a DML statement on a list is all-or-nothing. If one record fails validation, the whole statement fails and none of the records are saved. The Database methods let you change that with the allOrNone argument:
public class TaskCreator {
public static void createFollowUps(List<Account> accounts) {
List<Task> tasks = new List<Task>();
for (Account a : accounts) {
tasks.add(new Task(WhatId = a.Id, Subject = 'Follow up'));
}
if (tasks.isEmpty()) {
return;
}
List<Database.SaveResult> results = Database.insert(tasks, false);
for (Integer i = 0; i < results.size(); i++) {
if (!results[i].isSuccess()) {
for (Database.Error err : results[i].getErrors()) {
System.debug(
LoggingLevel.ERROR,
'Task for Account ' + tasks[i].WhatId + ' failed: '
+ err.getStatusCode() + ' ' + err.getMessage()
);
}
}
}
}
}With allOrNone set to false, valid records save and failed ones come back in the result list. The result list has the same order as the input list, so index i in results matches index i in tasks.
Partial success is still one DML statement and the rows still count against the limit. The choice is about correctness. Use all-or-nothing when the records belong together. Use partial success for independent records, such as a bulk import where one bad row should not block the rest. If you do not inspect the results, failures pass silently.
Hidden loops
DML inside a loop is not always visible. These patterns cause the same failure:
- A helper method that runs DML and is called from inside a loop. The loop looks clean, but each call spends one statement.
- A trigger handler that runs per record instead of per list.
- Code in
try/catchinside a loop, where a catch block saves an error log record on each failure. - Two triggers on different objects that update each other's records, so each fire adds more statements to the same transaction.
The fix is the same each time. Change the helper's signature so it accepts a List or Map, run it once, and let it do the single DML at the end. A method that takes Account a and ends in insert is a warning sign, while a method that takes List<Account> accounts fits the bulk pattern.
Bulk-safe does not mean unlimited
Collecting DML fixes the statement count. The 10,000-row limit still applies, and it is easy to hit when one input record produces many output records. If each of 200 Accounts creates 60 Tasks, that is 12,000 rows in one statement, and the transaction fails with Too many DML rows: 12001.
Options when the row count is a risk:
- Reduce what you create. Check whether every output record is actually required.
- Move the work to Queueable or Batch Apex, where each execution gets its own limits. A later chapter covers this.
- Use
Limits.getDmlRows()to see how much of the budget you have used. The chapter on theLimitsclass covers it in detail.
Verifying the result
A test that inserts 200 records shows quickly whether your DML is bulk-safe. This test uses the trigger from earlier in this chapter:
@IsTest
private class AccountAfterDmlTest {
@IsTest
static void usesOneDmlStatementForTasks() {
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 200; i++) {
accounts.add(new Account(Name = 'DML Test ' + i));
}
Test.startTest();
insert accounts;
Integer statements = Limits.getDmlStatements();
Test.stopTest();
System.assertEquals(
200,
[SELECT COUNT() FROM Task WHERE Subject = 'Follow up']
);
System.assert(
statements < 10,
'Expected few DML statements but used ' + statements
);
}
}Test.startTest() resets the counters, so Limits.getDmlStatements() after the insert includes the insert you ran (1) and the trigger's insert tasks (1). The exact number can change if other automation is added to the org, so assert a small upper bound instead of an exact value. If the trigger still had the loop version, this test would fail with a limit exception before reaching the assertions.
Common mistakes
- Putting
insertorupdateinside aforloop, directly or through a helper method. - Adding the same Id to an update list more than once. Use a
Map<Id, SObject>to deduplicate. - Calling
update Trigger.newin a before trigger. Assign field values instead. - Ignoring the results of
Database.insert(records, false). Failed records go unreported. - Treating bulkification as a fix for the row limit. One statement can still exceed 10,000 rows.
Exercise
A trigger on Contact (after insert) must set Description on each parent Account. A batch of 200 Contacts belongs to 5 Accounts. The current code adds one new Account(Id = c.AccountId, ...) to a List<Account> for every Contact and then calls update accountList. What error occurs, and how would you change the code?
Show answer
The update fails with System.ListException: Duplicate id in list, because the same Account Id appears many times in the list. Replace the List<Account> with a Map<Id, Account>. In the loop, call put(c.AccountId, new Account(Id = c.AccountId, ...)) so each Account is stored once. After the loop, call update accountMap.values() once, inside an isEmpty() check. This uses one DML statement and 5 DML rows.
Exercise
A trigger receives 200 Accounts and creates 60 Tasks for each, using one insert on a single list after the loop. The statement count is 1. Will the transaction succeed? Explain.
Show answer
No. The list holds 12,000 records, which exceeds the 10,000 DML rows limit, so the insert throws a limit exception. Collecting DML fixes the statement limit, not the row limit. Reduce the number of Tasks created, or move the work to Queueable or Batch Apex so that it runs in smaller transactions with their own limits.