Sub topic 10
Partial Success with Database.insert and SaveResult
This chapter assumes you can write basic Apex classes and methods, run SOQL queries and DML statements, and know that a transaction is the unit of work that governor limits apply to. It also assumes you have seen try, catch, and DmlException from the previous chapters.
The default is all or nothing
The insert statement is atomic across the records you give it. If you insert 200 accounts and one is invalid, Apex throws a DmlException and none of the 200 are saved.
That behavior is right when the records belong together, such as an order and its line items. It is wrong when the records are independent. Think of a nightly import of 10,000 leads where one bad email address should not block the other 9,999.
The Database class gives you a second option. Its DML methods take an allOrNone flag. When you pass false, Apex saves every record that is valid and reports the failures to you as data instead of throwing an exception.
Calling Database.insert with allOrNone
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 is saved. The second has no Name, so it fails. No exception is thrown, and the loop prints something like REQUIRED_FIELD_MISSING: Required fields are missing: [Name] (Name).
Compare the two call forms:
| Call | On a failing record | Result |
|---|---|---|
| `insert accts;` | Throws `DmlException` | Nothing saved |
| `Database.insert(accts)` | Throws `DmlException` (`allOrNone` defaults to `true`) | Nothing saved |
| `Database.insert(accts, true)` | Throws `DmlException` | Nothing saved |
| `Database.insert(accts, false)` | Returns normally | Valid records saved, failures in results |
Reading a SaveResult
Database.insert and Database.update return a List<Database.SaveResult>. Each element describes one input record. These are the members you use most:
isSuccess()returnstrueif the record was saved.getId()returns the record Id, ornullif the save failed.getErrors()returns aList<Database.Error>. It is empty on success.
Each Database.Error has three methods:
getStatusCode()returns aStatusCodeenum value such asREQUIRED_FIELD_MISSING,FIELD_CUSTOM_VALIDATION_EXCEPTION, orDUPLICATE_VALUE.getMessage()returns the human-readable text.getFields()returns the field names involved. It can be empty for errors that apply to the whole record.
Prefer comparing getStatusCode() with an enum value over matching text in getMessage(). Messages can change, and they can be translated. Status codes are stable.
if (err.getStatusCode() == StatusCode.DUPLICATE_VALUE) {
// handle duplicates differently from other errors
}A single record can have more than one error, so always loop over getErrors().
Matching results to input records
The results list has the same size and order as the input list. Index i in the results is the outcome for index i in the input. This is how you find out which record failed. The SaveResult itself does not contain the record.
public class LeadImporter {
public class ImportFailure {
public Integer index;
public String externalKey;
public String message;
}
public static List<ImportFailure> importLeads(List<Lead> leads) {
List<ImportFailure> failures = new List<ImportFailure>();
List<Database.SaveResult> results = Database.insert(leads, false);
for (Integer i = 0; i < results.size(); i++) {
if (results[i].isSuccess()) {
continue;
}
ImportFailure f = new ImportFailure();
f.index = i;
f.externalKey = leads[i].Email;
f.message = results[i].getErrors()[0].getMessage();
failures.add(f);
}
return failures;
}
}The method returns a list of failures that the caller can log, show to a user, or retry. Do not sort or reorder the input list between the DML call and the loop, or the indexes will no longer line up.
On success, Apex also writes the new Id back onto the input record, so leads[i].Id is set. On failure, Id stays null.
Other Database methods
The same pattern applies to the other DML operations. Only the result type changes.
| Method | Returns |
|---|---|
| `Database.insert(records, allOrNone)` | `List<Database.SaveResult>` |
| `Database.update(records, allOrNone)` | `List<Database.SaveResult>` |
| `Database.upsert(records, allOrNone)` | `List<Database.UpsertResult>`, which adds `isCreated()` |
| `Database.delete(records, allOrNone)` | `List<Database.DeleteResult>` |
| `Database.undelete(records, allOrNone)` | `List<Database.UndeleteResult>` |
All of these result types have isSuccess(), getId(), and getErrors().
Partial success does not remove exceptions
Setting allOrNone to false only changes how record-level errors are reported. Several problems still throw exceptions:
- Passing a
nulllist throws aNullPointerException. - Exceeding a governor limit, such as DML rows or DML statements, throws a
LimitException. You cannot catch it, as a later chapter explains. - Errors that are not tied to one record, such as inserting a record of the wrong object type into a typed list, can still throw.
Partial success also does not make the call cheaper. The call counts as one DML statement, and every record counts toward the 10,000-row DML limit, whether it succeeds or fails.
Triggers and partial success
Each record that fails in a trigger through addError() or a validation rule appears in the SaveResult as a failure. Records are processed in chunks of up to 200. When a record in a chunk fails during a partial-success call, Salesforce can rerun trigger logic for the records that remain. Write triggers so that running more than once for the same record does not cause side effects. Avoid sending an email or incrementing a counter inside a trigger without a guard.
Combining partial success with savepoints
Partial success is per call. Several Database calls in one transaction are still one transaction, and later code can still fail the whole thing. If you need several steps to succeed together, use a savepoint as in the rollback chapter. If you need each record handled independently, use allOrNone = false. Mixing them is possible, but decide for each step which one you need.
Testing partial success
Test both the saved record and the reported failure.
@IsTest
private class LeadImporterTest {
@IsTest
static void reportsFailuresAndSavesValidRecords() {
List<Lead> leads = new List<Lead>{
new Lead(LastName = 'Valid', Company = 'Acme', Email = '[email protected]'),
new Lead(Company = 'Missing Last Name', Email = '[email protected]')
};
List<LeadImporter.ImportFailure> failures = LeadImporter.importLeads(leads);
Assert.areEqual(1, failures.size(), 'One record should fail');
Assert.areEqual(1, failures[0].index);
Assert.areEqual('[email protected]', failures[0].externalKey);
Assert.areEqual(1, [SELECT COUNT() FROM Lead WHERE Email = '[email protected]']);
}
}The test checks that the failure is identified by position and that the valid lead was committed to the database.
Choosing between the two styles
- Use the
insertstatement orDatabase.insert(records, true)when the records depend on each other, and a failure should stop the whole operation. - Use
Database.insert(records, false)when records are independent, and users prefer partial progress over a total rollback. Plan how you report failures. - Wrap the all-or-nothing form in
try/catchforDmlException. Loop over theSaveResultlist for the partial form. Do not expect one style to behave like the other.
Exercise
You call Database.insert(contacts, false) with 50 contacts, and 3 fail validation. How many SaveResult objects are returned, and how do you find the name of the first failed contact?
Show answer
Fifty SaveResult objects are returned, one per input record, in the same order as the input list. Loop with an index, and when results[i].isSuccess() is false, read contacts[i]. For example, contacts[i].LastName gives the name. The SaveResult holds only the Id and errors, not the record, so you must use the index to match them.
Exercise
A teammate writes Database.insert(accts, false); and ignores the return value. What goes wrong, and what is the fix?
Show answer
Records that fail validation are skipped without any exception, error message, or log. The caller believes every account was saved. The fix is to store the returned List<Database.SaveResult>, check isSuccess() for each element, and handle or report the errors from getErrors().