Sub topic 10
Bulkifying DML: collections instead of calls in loops
This chapter assumes you can write Apex classes and methods, use List, Set, and Map, write try/catch blocks, and know that Apex runs in transactions with governor limits. It builds on the earlier chapters on DML statements and Database methods. It covers how to structure code so that the number of DML calls stays small no matter how many records you process.
Why the loop pattern fails
Each DML statement and each Database method call counts against a per-transaction limit. The relevant synchronous limits are:
| Limit | Value per transaction |
|---|---|
| DML statements issued | 150 |
| Records processed by DML (rows) | 10,000 |
The first limit counts calls. The second counts records. A single insert of 200 records uses one statement and 200 rows. Two hundred separate inserts of one record each use 200 statements and 200 rows, so the transaction fails at statement 151 even though it touches few records.
The failure looks like this:
System.LimitException: Too many DML statements: 151A LimitException cannot be caught. The whole transaction is rolled back and the user sees the error.
The anti-pattern
The code below calls update once for every record in the loop.
List<Contact> contacts = [
SELECT Id, Title
FROM Contact
WHERE AccountId != null
LIMIT 500
];
for (Contact c : contacts) {
c.Title = 'Reviewed';
update c; // one DML statement per iteration
}With 500 contacts this uses 500 statements and fails after 150. It also fails in a surprising way: it works in a unit test with five records, then breaks in production when a data load or a trigger sends 200 records at once.
The fix: change the record in the loop, write after the loop
Use the loop only to prepare records. Collect them in a list, then issue one DML call after the loop.
List<Contact> contacts = [
SELECT Id, Title
FROM Contact
WHERE AccountId != null
LIMIT 500
];
List<Contact> toUpdate = new List<Contact>();
for (Contact c : contacts) {
if (c.Title != 'Reviewed') {
c.Title = 'Reviewed';
toUpdate.add(c);
}
}
if (!toUpdate.isEmpty()) {
update toUpdate; // one statement, up to 500 rows
}Three details matter here:
- The list holds only records that changed. This keeps the row count down and avoids pointless updates that fire triggers and validation.
- The
isEmpty()check is a habit rather than a requirement. DML on an empty list does not throw an error, but it still counts as a statement in some cases, and the check makes the intent clear. - The collection is passed to the DML operation once. The statement does not care whether it is
updateorDatabase.update.
Both approaches count the same way
Bulkification applies equally to DML statements and Database methods. Database.update(list, false) is one DML statement. Its allOrNone parameter changes how failures are reported, not how limits are counted. Moving from update to Database.update does not save you any statements, and a Database call inside a loop fails the same way a statement does.
You can check usage while the code runs with the Limits class:
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 200; i++) {
accounts.add(new Account(Name = 'Bulk test ' + i));
}
System.debug('Before: ' + Limits.getDmlStatements() + ' of ' + Limits.getLimitDmlStatements() + ' statements');
List<Database.SaveResult> results = Database.insert(accounts, false);
System.debug('After: ' + Limits.getDmlStatements() + ' of ' + Limits.getLimitDmlStatements() + ' statements');
System.debug('Rows: ' + Limits.getDmlRows() + ' of ' + Limits.getLimitDmlRows());Run this in Anonymous Apex and the statement count goes up by one while the row count goes up by 200.
Row limits still apply
Collections remove the statement problem, not the row problem. Once a transaction passes 10,000 DML rows, you get a LimitException with the message Too many DML rows: 10001. Rows from every DML call in the transaction add up, including rows changed by triggers and by flows that run in the same transaction.
If one job must touch more than 10,000 records, split the work across transactions with Batch Apex or Queueable Apex. Bulkification keeps statements low inside each transaction, and batching keeps rows low.
Common bulk patterns
Creating child records for many parents
Query once, loop once, insert once.
List<Account> accounts = [
SELECT Id, Name
FROM Account
WHERE Name LIKE 'Acme%'
LIMIT 200
];
List<Task> tasks = new List<Task>();
for (Account a : accounts) {
tasks.add(new Task(
Subject = 'Follow up with ' + a.Name,
WhatId = a.Id,
Status = 'Not Started'
));
}
if (!tasks.isEmpty()) {
insert tasks;
}Updating records you looked up by Id
When values come from another source, such as a Map keyed by Id, build the update list from the map instead of querying inside the loop.
Map<Id, Account> accountsById = new Map<Id, Account>([
SELECT Id, Description
FROM Account
WHERE Name LIKE 'Acme%'
]);
List<Contact> contacts = [
SELECT Id, AccountId, Description
FROM Contact
WHERE AccountId IN :accountsById.keySet()
];
for (Contact c : contacts) {
c.Description = 'Parent: ' + accountsById.get(c.AccountId).Description;
}
if (!contacts.isEmpty()) {
update contacts;
}The same rule applies to SOQL. A query inside a loop is limited to 100 queries per transaction, so IN :set outside the loop is the matching fix.
Avoiding duplicate Ids in one list
A single update list cannot contain the same record Id twice. If your loop might add one record more than once, DML fails with Duplicate id in list. Keep updates in a Map<Id, SObject> and call values().
Map<Id, Account> changes = new Map<Id, Account>();
for (Contact c : [SELECT Id, AccountId FROM Contact WHERE AccountId != null LIMIT 200]) {
// Several contacts can share one account. The map keeps one entry per Id.
changes.put(c.AccountId, new Account(Id = c.AccountId, Description = 'Has contacts'));
}
if (!changes.isEmpty()) {
update changes.values();
}Bulk DML with partial success
Bulkifying and partial success work together. After a bulk Database call, loop over the results to find the failures. The result list has the same order as the input list, so index i in the results matches index i in the input.
List<Contact> contacts = new List<Contact>{
new Contact(LastName = 'Smith'),
new Contact(), // LastName is required, so this record fails
new Contact(LastName = 'Jones')
};
List<Database.SaveResult> results = Database.insert(contacts, false);
List<String> failures = new List<String>();
for (Integer i = 0; i < results.size(); i++) {
if (!results[i].isSuccess()) {
Database.Error err = results[i].getErrors()[0];
failures.add('Row ' + i + ': ' + err.getStatusCode() + ' - ' + err.getMessage());
}
}
System.debug(failures);Collect failures into a list and report them once at the end. Writing a log record for each failure inside the loop would bring back the problem you just fixed.
Edge cases to know
- Triggers receive batches. A trigger runs once per chunk of up to 200 records, with
Trigger.newholding all of them. Code in a trigger must treatTrigger.newas a collection, and DML inside it counts toward the same transaction totals as the code that fired it. - Triggers add to the count. If your
insertfires a trigger that issues its own DML, those statements and rows share the transaction's limits. A method that looks cheap can cost much more once automation runs. - Mixed record types in one list. A
List<SObject>can hold different object types, and DML accepts it. Salesforce splits the list into chunks of the same type, and an alternating order such as Account, Contact, Account, Contact creates many chunks. A single operation allows at most 10 chunks, so sort the list by type or use separate typed lists. - Setup and non-setup objects. Some objects, such as
User, cannot be changed in the same transaction as ordinary objects likeAccount. This mixed DML error is unrelated to bulkification, but putting both in one list will not avoid it. - Test the bulk case. Write at least one unit test that runs your code with 200 or more records. A test with three records cannot reveal a DML-in-loop bug.
Quick checklist
- No
insert,update,upsert,delete,undelete, orDatabase.*call sits inside afororwhileloop. - Records are added to a
ListorMapand written once. - The list holds only changed records and has no duplicate Ids.
- Volume above 10,000 rows is split with Batch or Queueable Apex.
- A test exercises the code with 200 or more records.
Exercise
A method updates 300 contacts by calling Database.update(c, false) inside a for loop, once per contact. Does the allOrNone value of false prevent the "Too many DML statements: 151" error? How should the method be changed?
Show answer
No. The allOrNone parameter only controls whether record-level failures abort the call. Each Database.update call is still one DML statement, so 300 calls exceed the limit of 150. Add each changed contact to a List<Contact> inside the loop, then call Database.update(list, false) once after the loop. That uses one statement and 300 rows.
Exercise
A loop adds Account records to a list for update, but several Contacts share the same parent Account, so the same Account Id is added more than once. What error does this cause, and what collection avoids it?
Show answer
DML fails with a "Duplicate id in list" error. Store the accounts in a Map<Id, Account> keyed by Id, so each Id appears once, and pass map.values() to the update call.