Sub topic 5
allOrNone: all-or-nothing versus partial success
This chapter assumes you can write Apex classes and methods, work with List<SObject> collections, use try/catch, and know that Apex runs inside a transaction with governor limits. Earlier chapters covered the DML statements (insert, update) and the Database class methods. This chapter covers the setting that makes them behave differently when some records in a list are invalid.
The question allOrNone answers
When you save a list of 200 records and one is invalid, Apex has to decide between two outcomes:
- All-or-nothing: none of the 200 records are saved, and you are told about the failure.
- Partial success: the 199 valid records are saved, and the failed record is reported to you.
The allOrNone parameter selects between these. It is a Boolean that you pass to the Database methods (Database.insert, Database.update, Database.upsert, Database.delete, Database.undelete). It defaults to true.
| Call | Behavior when one record fails | How you learn about the failure |
|---|---|---|
| `insert records;` | Whole statement rolls back | `DmlException` is thrown |
| `Database.insert(records)` | Same as the statement (default `true`) | `DmlException` is thrown |
| `Database.insert(records, true)` | Whole call rolls back | `DmlException` is thrown |
| `Database.insert(records, false)` | Valid records are saved, invalid ones are not | Result objects, no exception for record-level errors |
DML statements have no allOrNone switch. They are always all-or-nothing. That is the main reason the Database methods exist.
All-or-nothing in practice
Here is the statement form with one invalid record. Name is required on Account, so the second record fails.
List<Account> accounts = new List<Account>{
new Account(Name = 'Acme'),
new Account() // Name is required, so this record fails
};
try {
insert accounts;
} catch (DmlException e) {
System.debug('Failed rows: ' + e.getNumDml());
System.debug(e.getMessage());
}
System.debug('Accounts saved: ' + [SELECT COUNT() FROM Account WHERE Name = 'Acme']);The Acme record is not saved, even though it was valid. The statement is atomic. The DmlException carries per-record detail through methods such as getNumDml(), getDmlIndex(i), getDmlStatusCode(i), getDmlMessage(i), and getDmlFieldNames(i).
Passing true explicitly to a Database method gives the same behavior:
List<Account> accounts = new List<Account>{
new Account(Name = 'Acme'),
new Account()
};
try {
Database.insert(accounts, true);
} catch (DmlException e) {
for (Integer i = 0; i < e.getNumDml(); i++) {
System.debug('Row ' + e.getDmlIndex(i) + ': '
+ e.getDmlStatusCode(i) + ' - ' + e.getDmlMessage(i));
}
}Use all-or-nothing when the records form one logical unit. An order and its line items are an example. Saving only some of them would leave inconsistent data.
Partial success with allOrNone set to false
Passing false changes two things. Valid records are committed to the transaction, and Apex does not throw for record-level errors. It returns an array of result objects instead.
List<Account> accounts = new List<Account>{
new Account(Name = 'Acme'),
new Account() // Name is required, so this record fails
};
List<Database.SaveResult> results = Database.insert(accounts, false);
for (Integer i = 0; i < results.size(); i++) {
Database.SaveResult sr = results[i];
if (sr.isSuccess()) {
System.debug('Inserted ' + sr.getId());
} else {
for (Database.Error err : sr.getErrors()) {
System.debug('Record ' + i + ' failed: ' + err.getStatusCode()
+ ' - ' + err.getMessage() + ' ' + err.getFields());
}
}
}The results list has one entry per input record, in the same order. results[1] describes accounts[1]. The next two chapters cover the result objects and the error details in depth. For now, remember the shape: one result per record, matched by index.
The decision flow looks like this:
The danger of silent failure
With false, a failed save does not interrupt your code. If you ignore the return value, the failure disappears.
// Anti-pattern: errors are swallowed
Database.insert(accounts, false);This line compiles, runs, and may save only some of the records, with no sign that anything went wrong. Whenever you pass false, you take on the job of reading the results. At a minimum, capture the return value and check isSuccess() for every entry.
What allOrNone does not change
The parameter only affects record-level failures such as validation rule errors, missing required fields, or a trigger calling addError() on a record. Some problems still throw an exception even when allOrNone is false:
- Governor limit violations, such as too many DML statements or DML rows. These end the transaction with an uncatchable
LimitException. - Mixed DML errors, where you modify setup objects (such as
User) and non-setup objects (such asAccount) in the same transaction. - Programming errors, such as passing a
nulllist or a list that has the wrong structure for the operation.
Treat allOrNone as a control for data problems in individual records, not as a general error suppressor.
Transaction scope: what "rolled back" means
"The whole call rolls back" means that one DML call is undone. It does not mean the whole transaction. Consider this sequence:
insert new Account(Name = 'First'); // succeeds
List<Account> batch = new List<Account>{
new Account(Name = 'Second'),
new Account() // fails
};
try {
insert batch; // statement rolls back
} catch (DmlException e) {
System.debug('Caught: ' + e.getMessage());
}
// 'First' is still saved in this transaction. 'Second' is not.If you catch the DmlException, the earlier First insert stays in the transaction and is committed when the transaction finishes normally. If you do not catch it, the exception propagates and Salesforce rolls back the entire transaction, including First. To undo work from earlier statements deliberately, use a savepoint, which a later chapter covers.
Partial success and triggers
When a call runs with allOrNone set to false, record-level failures can come from validation rules, required fields, or trigger code. If a trigger calls addError() on one record, only that record fails and the rest can be saved. Apex may then process the remaining records again after removing the failed ones, so triggers and automation can run more than once for the same call. Do not put side effects in a trigger that assume it runs exactly once per record. Make the logic safe to repeat.
Choosing a setting
| Situation | Setting | Reason |
|---|---|---|
| Parent and children must exist together | All-or-nothing | A partial save leaves orphaned or incomplete data |
| Importing many independent rows, where bad rows can be reported and fixed later | `false` | One bad row should not block the rest |
| User-facing form saving a single record | All-or-nothing | One record has nothing to partially save, and the exception is simple to show |
| Integration that must report row-level outcomes to a caller | `false` | You need a success or failure result for each record |
The same trade-off appears in each row. Partial success keeps good data flowing and gives per-record feedback, but you must write the code that reads and acts on the results. All-or-nothing is simpler and keeps data consistent, but one bad record blocks the entire list.
Setting allOrNone through DMLOptions
Database.DMLOptions also exposes this setting as optAllOrNone. It is useful when you already need an options object for something else. The later chapter on DMLOptions covers it. This example shows the equivalence:
Database.DMLOptions opts = new Database.DMLOptions();
opts.optAllOrNone = false;
List<Account> accounts = new List<Account>{
new Account(Name = 'Acme'),
new Account()
};
List<Database.SaveResult> results = Database.insert(accounts, opts);
System.debug('First saved: ' + results[0].isSuccess());
System.debug('Second saved: ' + results[1].isSuccess());The output is true for the first record and false for the second. This matches Database.insert(accounts, false).
Common mistakes
- Assuming a
Databasemethod with the default setting allows partial success.Database.insert(accounts)is all-or-nothing, the same as the statement. You must passfalse. - Ignoring the returned list. Failures are then invisible.
- Reading results by position after reordering or filtering the input list. Result
imatches inputionly for the exact list you passed. - Expecting
try/catchto catch record errors whenallOrNoneisfalse. Those errors arrive as result objects, not exceptions. Keep thetry/catchfor the exceptions that can still occur, such as mixed DML errors. - Assuming earlier DML is undone when you catch an exception. Only the failed call is rolled back.
Exercise
A developer writes Database.update(contacts); and is surprised that no contacts were updated when one contact failed a validation rule. No exception handling is in place. What happened, and what is the smallest change that lets the valid contacts save?
Show answer
With no second argument, allOrNone defaults to true, so the call behaves like an update statement: one failure rolls back every record and throws a DmlException (which, uncaught, also rolls back the whole transaction). The smallest change is List<Database.SaveResult> results = Database.update(contacts, false);, followed by a loop that checks isSuccess() on each result so that failures are not silently ignored.
Exercise
You call Database.insert(accounts, false) with 50 accounts. results.size() is 50, and results[7].isSuccess() is false. Which input record failed, and does a try/catch around the call report that failure?
Show answer
The failed record is accounts[7], because the results list is in the same order as the input list. A try/catch does not report it. With allOrNone set to false, record-level errors are returned in the result objects and no DmlException is thrown for them. You must read results[7].getErrors() to see the status code, message, and fields.