Sub topic 4
All-or-None Behavior of a Single DML Statement
This chapter assumes you can write Apex classes and methods, run insert and update on sObjects, and use try/catch with DmlException. It also assumes you know that governor limits exist. You don't need savepoints yet. They come later.
The Rule: One Statement, One Outcome
A DML statement that works on a list of records either saves every record or saves none of them. This is called all-or-none behavior, or statement-level atomicity. Atomic means the statement can't be half done.
Suppose you insert three accounts and the second has no Name. Name is required, so that record fails. Because the statement is all-or-none, the first and third accounts are not saved either. Apex then throws a DmlException.
Integer before = [SELECT COUNT() FROM Account WHERE Name LIKE 'Batch%'];
List<Account> accts = new List<Account>{
new Account(Name = 'Batch One'),
new Account(), // Name is required, so this record fails
new Account(Name = 'Batch Three')
};
try {
insert accts;
} catch (DmlException e) {
System.debug('Insert failed: ' + e.getMessage());
}
Integer after = [SELECT COUNT() FROM Account WHERE Name LIKE 'Batch%'];
System.debug('Accounts added: ' + (after - before)); // 0The debug line prints 0. "Batch One" was valid, but it was rolled back with the failing record. The exception message names the row of the first failure, for example Insert failed. First exception on row 1; first error: REQUIRED_FIELD_MISSING .... Row numbers start at 0, so row 1 is the second record.
What the Rule Covers
All-or-none applies to every DML statement form: insert, update, upsert, delete, undelete, and merge. It also applies to the Database class methods when you leave allOrNone at its default, which is true.
| Call | allOrNone | A record fails |
|---|---|---|
| `insert list;` | always true | Nothing is saved. A `DmlException` is thrown. |
| `Database.insert(list)` | true by default | Nothing is saved. A `DmlException` is thrown. |
| `Database.insert(list, true)` | true | Nothing is saved. A `DmlException` is thrown. |
| `Database.insert(list, false)` | false | Valid records are saved. Failures are returned in the results. |
The last row is partial success. The next chapter covers it. For now, remember that a plain DML statement never gives you partial success.
What Counts as a Failure
Any error that is tied to a record can fail the statement. Common causes are:
- A required field is missing.
- A field value is the wrong type or too long.
- A validation rule fails.
- A duplicate rule blocks the save.
- A trigger calls
addErroron a record. - A trigger throws an exception, or runs code that does.
- The user lacks permission to edit a record in the list.
The timing of the failure doesn't matter. A record can pass field checks and fail in an after trigger. The whole statement is still rolled back, including records that were fine. A single bad record anywhere in the list decides the result for all of them.
Inspecting a Failure
The DmlException carries per-record detail. Use these methods to see which records failed and why:
getNumDml()returns the number of failed records.getDmlIndex(i)returns the position in your list of the i-th failed record.getDmlMessage(i)returns the error text for that record.getDmlStatusCode(i)returns a code such asREQUIRED_FIELD_MISSING.getDmlFieldNames(i)returns the fields involved.
List<Account> accts = new List<Account>{
new Account(Name = 'Valid'),
new Account()
};
try {
Database.insert(accts); // same as: insert accts;
} catch (DmlException e) {
for (Integer i = 0; i < e.getNumDml(); i++) {
System.debug(
'List index ' + e.getDmlIndex(i) + ': ' +
e.getDmlStatusCode(i) + ' - ' + e.getDmlMessage(i)
);
}
}The output reports index 1 only. The first account didn't fail on its own, so it isn't listed. It was still not saved.
How the Statement Is Processed
The flow below shows what the platform does with a list. Records are handled in chunks of 200 for trigger execution, but the all-or-none decision covers the whole statement. A failure in the last chunk undoes the records in the earlier chunks.
Statement-Level Versus Transaction-Level
The rollback in this chapter covers one statement only. Earlier DML in the same transaction is not touched by it. This distinction is easy to miss, so here is an example.
insert new Account(Name = 'Earlier Statement');
try {
insert new List<Account>{
new Account(Name = 'Same Statement'),
new Account()
};
} catch (DmlException e) {
System.debug('Second statement failed: ' + e.getDmlMessage(0));
}
// 'Earlier Statement' is saved (pending commit). 'Same Statement' is not.The first insert is a separate statement that already succeeded. The failing statement undoes only its own records. If the exception had not been caught, it would have ended the whole transaction, and the platform would have rolled back everything. That case is covered in the chapter on unhandled exceptions. The next chapter covers what happens when you catch the exception, and how to undo earlier statements on purpose.
One Statement or Many
Because a statement is atomic and counts once against limits, you usually want one DML statement per operation, run on a list. Compare these two loops.
// Avoid: one DML statement per record
List<Account> accts = new List<Account>{
new Account(Name = 'Loop A'),
new Account(Name = 'Loop B')
};
for (Account a : accts) {
insert a;
}
// Prefer: one DML statement for the whole list
insert accts;The loop uses one DML statement per record, and the limit is 150 statements per transaction. The list form uses one statement. The behaviors also differ. In the loop, a failure on record 2 leaves record 1 saved, because each statement is its own unit. In the list form, a failure on record 2 saves nothing. Choose by what you need: if the records belong together, use one statement. If each record should stand alone, use partial success, not a loop of single inserts.
Edge Cases to Remember
- Large lists. A list of 1,000 records is processed in chunks for triggers. One failure in any chunk still undoes all 1,000.
- Single records.
insert acct;on one record behaves the same way. The statement either saves it or fails. - Uncaught exceptions. If you don't catch the
DmlException, the whole transaction is rolled back, not only the failing statement. - Limits are not refunded. A failed statement still counts as one DML statement against the limit, and its rows still count toward the 10,000-row limit.
- Results of the retry. If you catch the exception and fix the data, you can run the statement again. The records start from a clean state because nothing was saved.
Exercise
A method runs insert new Account(Name = 'First');, then in a try block runs insert new List<Account>{ new Account(Name = 'Second'), new Account() }; and catches the DmlException. How many of these accounts exist in the transaction afterward, and why? What changes if the second statement is Database.insert(list, false) and nothing is thrown?
Show answer
One account, 'First'. The first statement succeeded on its own. The second statement is all-or-none, so 'Second' is rolled back because the other record has no required Name. With Database.insert(list, false) the valid 'Second' record is saved and only the invalid record fails, so two accounts exist. The failure is reported in the returned SaveResult instead of an exception.
Exercise
You catch a DmlException from insert accts;, where accts holds 500 records. The exception reports getNumDml() as 1 with getDmlIndex(0) equal to 499. How many of the 500 records were saved?
Show answer
None. The statement is all-or-none across the whole list, even though triggers run in chunks of 200. The failure in the final record undoes the other 499.