Sub topic 10
Bulkifying DML: collections instead of calls in loops
This chapter assumes you know basic Apex syntax, collections, SObjects, try/catch, and that Apex runs in transactions with governor limits. It covers one pattern: how to bulkify DML so it stays inside the limits, whichever API you use.
Why DML in a loop fails
A governor limit caps how many DML statements one transaction can run. In synchronous Apex the cap is 150 DML statements per transaction. The cap applies to both insert and Database.insert, and each call counts as one statement. The number of records in a call does not change that count. A separate limit caps the total rows processed at 10,000 per transaction.
A call inside a loop runs once per iteration. With 200 records, the following code attempts 200 statements and fails after the 150th with a System.LimitException. You cannot catch that exception, so the whole transaction fails.
List<Account> accounts = [SELECT Id, Name FROM Account LIMIT 200];
for (Account a : accounts) {
a.Description = 'Reviewed';
update a; // one DML statement per iteration
}The fix: collect, then write once
Bulkifying means moving the DML call out of the loop. Inside the loop you change records and add them to a collection. After the loop, one call saves the whole collection.
List<Account> accounts = [SELECT Id, Name FROM Account LIMIT 200];
List<Account> toUpdate = new List<Account>();
for (Account a : accounts) {
a.Description = 'Reviewed';
toUpdate.add(a);
}
update toUpdate; // one DML statement for all recordsThis uses one statement for 200 records. The Database methods follow the same rule. Pass the list to a single call:
List<Database.SaveResult> results = Database.update(toUpdate, false);Do not forget DML hidden in called code
DML in a loop is not always visible. A loop may call a method, and that method may run DML. Every call still counts toward the same transaction limit. Triggers add to this. A single update on 200 records fires the trigger once for the batch, so the trigger must also handle the whole Trigger.new collection and not process one record at a time.
When one list holds several SObject types, DML needs a separate call for each type. Group the records by type first. You can pass a list of the generic SObject type, but the records must be sorted by type, because each run of one type in the list counts as a chunk. Many chunks can still hit the limit. The simplest approach is one typed list per object and one call for each.
List<Account> newAccounts = new List<Account>();
List<Contact> newContacts = new List<Contact>();
for (Integer i = 0; i < 100; i++) {
newAccounts.add(new Account(Name = 'Acct ' + i));
}
insert newAccounts;
for (Account a : newAccounts) {
newContacts.add(new Contact(LastName = 'Main', AccountId = a.Id));
}
insert newContacts; // 2 statements total, 200 rowsCommon errors
- Putting
updateorDatabase.updateinside aforloop, which fails with a limit exception at 150 statements. - Calling a helper method that runs DML from inside a loop.
- Updating the same record twice in one list. A list can hold the same Id only once in an
update, or the call fails with a duplicate id error. - Reading a result list as if it only covered successful rows. With
allOrNonefalse, the result list has one entry for every input record.
Exercise
A loop over 500 contacts calls Database.update(c, false) on each one. Why does this fail, and how do you fix it?
Show answer
Each call counts as one DML statement, so the transaction reaches the 150 statement limit and throws an uncatchable LimitException. Add each changed contact to a List<Contact> inside the loop, then call Database.update(list, false) once after the loop. This uses one statement for all 500 records.