Sub topic 10
Partial success with Database.insert and SaveResult
This chapter assumes you know basic Apex syntax, SOQL and DML statements, and how transactions work. It also assumes you have read the previous chapter on handling DmlException.
Why use partial success
The insert statement is all or nothing. If one record in a list fails, Apex throws a DmlException and none of the records are saved. That is often what you want. But when you load many independent records, one bad row should not block the rest.
The Database class offers methods that match each DML statement, such as Database.insert, Database.update, Database.upsert, and Database.delete. Each takes an optional allOrNone argument. Pass false to allow partial success.
| Approach | Failure behavior | How you see errors |
|---|---|---|
| `insert list;` | No records saved | `DmlException` is thrown |
| `Database.insert(list, true)` | No records saved | `DmlException` is thrown |
| `Database.insert(list, false)` | Valid records saved | Errors returned in `SaveResult` objects |
Reading the results
With allOrNone set to false, the method returns a List<Database.SaveResult>. The list has one entry per input record, in the same order. Each SaveResult tells you whether that record saved.
List<Account> accts = new List<Account>{ new Account(Name = 'Valid'), new Account() };
List<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() + ' ' + err.getFields());
}
}
}The first account has a name, so it saves. The second has no Name, so it fails. No exception is thrown. The failure appears in the second SaveResult.
Useful members:
isSuccess()returnstrueif the record saved.getId()returns the new record Id, ornullon failure.getErrors()returns a list ofDatabase.Errorobjects.Database.Error.getStatusCode()returns aStatusCodevalue such asREQUIRED_FIELD_MISSING.Database.Error.getMessage()returns the readable message.Database.Error.getFields()returns the fields involved.
Matching results to records
Because results follow input order, you can use the index to find the failed record.
List<Contact> contacts = new List<Contact>{
new Contact(LastName = 'Rivera'),
new Contact(FirstName = 'NoLastName')
};
List<Database.SaveResult> results = Database.insert(contacts, false);
List<Contact> failed = new List<Contact>();
for (Integer i = 0; i < results.size(); i++) {
if (!results[i].isSuccess()) {
failed.add(contacts[i]);
}
}
System.debug(failed.size() + ' contact(s) failed');Common errors
- Ignoring the results. With
allOrNoneset tofalse, failures are silent unless you check eachSaveResult. Code that discards the return value loses errors without any sign of a problem. - Expecting an exception. Validation failures, required fields, and rule violations are returned as errors. Some problems still throw, such as a null list or a governor limit exceeded.
- Assuming a rollback. Records that saved stay saved within the transaction. If later logic fails, use a savepoint, covered in a later chapter.
Exercise
You call Database.insert(records, false) with 200 records and 5 fail validation. How many exceptions are thrown, and how do you find the 5 failures?
Show answer
No DmlException is thrown for the validation failures. 195 records are saved. Loop through the returned List<Database.SaveResult>, check isSuccess() on each, and use the index to match each failed result to its record in the input list. Read the problems with getErrors().