Sub topic 5
Partial Success with Database.insert and allOrNone
This chapter assumes you can write basic Apex, run DML statements such as insert and update, and use try/catch with DmlException. You should also know that one transaction has shared governor limits. The previous chapter showed that a single DML statement is all-or-none. Here you will see how to turn that off, and what you must do yourself once you do.
The allOrNone parameter
The insert keyword treats a list of records as one unit. If one record fails validation, no record in the list is saved and Apex throws a DmlException.
The Database class offers the same operations as methods. Each method takes an optional Boolean parameter named allOrNone:
Database.SaveResult[] results = Database.insert(records, false);trueis the default. It behaves like theinsertkeyword, so any record failure throws aDmlExceptionand nothing from that statement is saved.falseenables partial success. Records that pass are saved, and records that fail are skipped. Apex does not throw for record-level failures. It reports them in the returned array.
| Call | A record fails | Records that were valid | How you learn about it |
|---|---|---|---|
| `insert records;` | Statement fails | Not saved | `DmlException` |
| `Database.insert(records)` | Statement fails | Not saved | `DmlException` |
| `Database.insert(records, true)` | Statement fails | Not saved | `DmlException` |
| `Database.insert(records, false)` | Only that record fails | Saved | `SaveResult` array |
The same pattern applies to the other DML methods. Database.update also returns Database.SaveResult[]. Database.upsert returns Database.UpsertResult[], Database.delete returns Database.DeleteResult[], and Database.undelete returns Database.UndeleteResult[]. The rest of this chapter uses insert, but the ideas carry over.
Reading a SaveResult
Each element of the returned array describes one input record. The array has the same length and order as the input list, so results[i] belongs to records[i].
A Database.SaveResult has three methods you will use most:
isSuccess()returnstrueif the record was saved.getId()returns the new record Id, ornullif the save failed.getErrors()returns a list ofDatabase.Errorobjects. The list is empty on success.
A Database.Error gives you getStatusCode(), which returns a System.StatusCode enum value such as REQUIRED_FIELD_MISSING. It also gives you getMessage(), a human-readable description, and getFields(), the field names involved. Compare status codes against the enum, not against message text, because messages can change and may be translated.
Here is the basic loop:
List<Account> accts = new List<Account>{
new Account(Name = 'Good'),
new Account() // missing required Name
};
Database.SaveResult[] results = Database.insert(accts, false);
for (Database.SaveResult sr : results) {
if (!sr.isSuccess()) {
for (Database.Error err : sr.getErrors()) {
System.debug(err.getStatusCode() + ': ' + err.getMessage());
}
}
}The first account is saved. The second is not, and the debug log shows REQUIRED_FIELD_MISSING with a message that names the Name field. No exception reaches your code.
Reporting failures with the row they came from
A failure message is more useful when it says which input row failed. Because results line up with the input by index, a plain for loop with a counter gives you that. This class returns a summary instead of logging:
public with sharing class AccountLoader {
public class LoadSummary {
public Integer saved = 0;
public List<String> failures = new List<String>();
}
public static LoadSummary insertAccounts(List<Account> accts) {
LoadSummary summary = new LoadSummary();
Database.SaveResult[] results = Database.insert(accts, false);
for (Integer i = 0; i < results.size(); i++) {
Database.SaveResult sr = results[i];
if (sr.isSuccess()) {
summary.saved++;
} else {
for (Database.Error err : sr.getErrors()) {
summary.failures.add(
'Row ' + i + ' (' + accts[i].Name + '): '
+ err.getStatusCode() + ' - ' + err.getMessage()
);
}
}
}
return summary;
}
}The caller can show summary.failures to a user, store it in a log object, or retry only the failed rows.
What partial success does not change
Partial success changes how one statement reports record failures. It does not change the transaction around it.
- Saved records are not committed yet. They are in the same open transaction as the rest of your work. If an unhandled exception occurs later, the whole transaction rolls back, including the records that
Database.insert(records, false)saved. - The call still counts as one DML statement against the limit, whether
allOrNoneistrueorfalse. Every record you pass counts toward the DML rows limit, including the ones that fail. - Some problems still throw. A governor limit exception, such as too many DML statements, is not a record-level failure. It is raised regardless of
allOrNone. The same is true of passing anulllist.
Triggers and partial success
Triggers interact with allOrNone in a useful way. When a trigger calls addError on a record, that record fails. Under allOrNone = true, one failed record fails the whole statement. Under allOrNone = false, only the marked records fail and the others proceed.
trigger ContactTrigger on Contact (before insert) {
for (Contact c : Trigger.new) {
if (c.Email == null) {
c.addError('Email is required');
}
}
}If you call Database.insert(contacts, false), contacts without an email come back as failed results carrying your message, and the rest are saved. Trigger and validation behavior is covered in its own chapter. The point here is that the caller decides whether one bad record sinks the batch.
Be aware that when a partial save has failures, the platform can run trigger logic again for the records that remain. Keep trigger code free of side effects that break if it runs twice for the same record, such as a static counter that you increment per record.
Handling related records after a partial save
Partial success becomes tricky when records depend on each other. If a parent record fails, its child records must not be created. Use the results to build the child list from the parents that succeeded:
List<Account> parents = new List<Account>{
new Account(Name = 'Parent One'),
new Account(), // fails: Name is required
new Account(Name = 'Parent Three')
};
Database.SaveResult[] parentResults = Database.insert(parents, false);
List<Contact> children = new List<Contact>();
for (Integer i = 0; i < parentResults.size(); i++) {
if (parentResults[i].isSuccess()) {
children.add(new Contact(
LastName = 'Primary ' + i,
AccountId = parentResults[i].getId()
));
}
}
insert children;If you skipped the check and built every child from parents[i].Id, the failed parent would give a null AccountId. Depending on your org, that child would insert as an orphan or fail on its own, and neither outcome is what you intended.
Choosing between the two modes
Use all-or-none (the default) when the records form one logical unit and a partial result would leave data inconsistent. An order and its line items are an example. A caught DmlException plus a savepoint, covered in later chapters, handles the failure.
Use partial success when records are independent and one bad row should not block the rest. Typical cases are data loads, integrations that receive batches, and cleanup jobs. You accept the cost of writing result-handling code.
Common errors
- Passing
falseand never reading theSaveResultarray. - Assuming a result array is shorter when records fail. It always has one entry per input record.
- Using
getErrors()[0]without checkingisSuccess()first. On success the list is empty and you get aListException. - Matching results to records by Id. Failed records have no Id, so match by index.
- Wrapping the call in
try/catchand expecting it to catch record-level failures. Withfalse, those arrive as results. You still catch limit exceptions and other statement-level errors.
Exercise
A method calls Database.insert(contacts, false) on a list of 200 contacts. Five fail validation. Later in the same transaction, the method throws an unhandled exception. How many of the 200 contacts exist in the database afterward, and why?
Show answer
None. Partial success only means the 195 valid contacts are saved into the open transaction while the five failures are reported in the SaveResult array. Nothing is committed until the transaction ends successfully. The unhandled exception rolls back the whole transaction, including the 195 saved contacts.
Exercise
You call Database.insert(accts, false) and want to log the input row number of each failure. Why should you use a counter-based loop over the results instead of looking records up by Id, and what does results[i] correspond to?
Show answer
Failed records have a null Id, so an Id lookup cannot find them. The result array has one entry per input record in the same order, so results[i] corresponds to accts[i]. A loop with an index lets you pair each failed result with its source record.