Sub topic 6
Reading SaveResult, UpsertResult, and DeleteResult
This chapter assumes you can write basic Apex, use try/catch, and know that Database methods accept an allOrNone flag. Here you learn what those methods return and how to read it. Detailed error inspection and matching results back to input records get their own chapters, so this one focuses on the result objects themselves.
Why result objects exist
A DML statement such as insert accounts; either succeeds for every record or throws a DmlException. A Database method called with allOrNone set to false behaves differently. It does not throw for record-level errors. It returns an array of result objects, and you decide what a failure means.
Each result object describes the outcome for one input record. That makes the result list the only record of what happened. If you ignore it, failed records disappear silently.
The three result classes
Each Database DML method returns a list of a specific result type.
| Database method | Returns | Used for |
|---|---|---|
| `Database.insert`, `Database.update` | `List<Database.SaveResult>` | Create and modify |
| `Database.upsert` | `List<Database.UpsertResult>` | Create or modify by ID or external ID |
| `Database.delete` | `List<Database.DeleteResult>` | Delete |
| `Database.undelete` | `List<Database.UndeleteResult>` | Restore from the Recycle Bin |
Database.UndeleteResult works like the others. It has getId(), isSuccess(), and getErrors().
The three main classes share a core set of methods.
| Method | Returns | Meaning |
|---|---|---|
| `isSuccess()` | `Boolean` | `true` if the operation succeeded for this record |
| `getId()` | `Id` | The record ID. For a failed insert, it is `null` |
| `getErrors()` | `List<Database.Error>` | The errors for this record. Empty on success |
UpsertResult adds isCreated(), which returns true if the upsert inserted a new record and false if it updated an existing one. For a failed upsert, the value of isCreated() is not meaningful, so check isSuccess() first.
Result order matches input order
The list you get back has the same size and order as the list you passed in. The record at index 3 of the input corresponds to the result at index 3. This is the property that lets you connect a failure to a specific record. Chapter material on partial success builds on it, but you can already rely on it here.
Reading a SaveResult
This example inserts three accounts. One has no Name, which is a required field, so that record fails.
List<Account> accounts = new List<Account>{
new Account(Name = 'Acme'),
new Account(),
new Account(Name = 'Globex')
};
List<Database.SaveResult> results = Database.insert(accounts, false);
Integer saved = 0;
Integer failed = 0;
for (Database.SaveResult sr : results) {
if (sr.isSuccess()) {
saved++;
System.debug('Saved record ' + sr.getId());
} else {
failed++;
System.debug('Failed with ' + sr.getErrors().size() + ' error(s)');
}
}
System.debug('Saved: ' + saved + ', failed: ' + failed);The output reports two saved records and one failed record. The two valid accounts are committed to the transaction, and the invalid one is not.
After a successful Database.insert, Salesforce also populates the Id field on the original Account objects in your list. For the failed record, the Id stays null. That gives you a second way to tell which records were saved, though isSuccess() is the clearer check.
Reading an UpsertResult
An upsert needs a way to decide whether a record already exists. You supply either the record Id or an external ID field. This example uses a hypothetical custom external ID field named External_Id__c on Account.
List<Account> accounts = new List<Account>{
new Account(Name = 'Acme', External_Id__c = 'A-100'),
new Account(Name = 'Globex', External_Id__c = 'G-200')
};
List<Database.UpsertResult> results = Database.upsert(accounts, Account.External_Id__c, false);
for (Integer i = 0; i < results.size(); i++) {
Database.UpsertResult ur = results[i];
if (ur.isSuccess()) {
String action = ur.isCreated() ? 'Created' : 'Updated';
System.debug(action + ' ' + accounts[i].External_Id__c + ' as ' + ur.getId());
} else {
System.debug('Upsert failed for ' + accounts[i].External_Id__c);
}
}Run it twice. The first run creates both records, so isCreated() returns true. The second run finds the matching external IDs and updates them, so isCreated() returns false.
Reading a DeleteResult
A DeleteResult has the same three core methods. getId() returns the ID of the record you tried to delete. This differs from a failed insert, where the ID is null, because the record already existed.
List<Account> toDelete = [SELECT Id FROM Account WHERE Name = 'Acme' LIMIT 5];
List<Database.DeleteResult> results = Database.delete(toDelete, false);
for (Database.DeleteResult dr : results) {
if (dr.isSuccess()) {
System.debug('Deleted ' + dr.getId());
} else {
for (Database.Error err : dr.getErrors()) {
System.debug('Could not delete ' + dr.getId() + ': ' + err.getMessage());
}
}
}Deletes fail for reasons that inserts do not. A record may be referenced by a lookup that blocks deletion, or the running user may lack delete permission. These show up as errors on the DeleteResult, not as exceptions, when allOrNone is false.
What the results contain when allOrNone is true
If you call Database.insert(records, true), or omit the second argument, the default is true. In that case any record-level failure throws a DmlException, just as a DML statement does. You still receive result objects when every record succeeds, but they all report success. The result list is only useful for failure analysis when allOrNone is false.
try {
List<Database.SaveResult> results = Database.insert(
new List<Account>{ new Account() }, true
);
System.debug('Not reached when a record fails');
} catch (DmlException e) {
System.debug('Exception thrown: ' + e.getMessage());
}Common mistakes
- Ignoring the return value. Calling
Database.insert(records, false);without assigning the result compiles and runs. Failed records are then lost with no log entry and no exception. - Assuming
getId()is set on a failure. For inserts and upserts that fail, it isnull. Use the input list index to identify the record. - Assuming a result list is shorter than the input. It is always the same length. Successes and failures appear in one list.
- Reading
getErrors()without checkingisSuccess(). On success the list is empty, so agetErrors()[0]access throws aListException. - Treating one error as the only error. A single record can have several errors, so loop over
getErrors()instead of reading only the first element.
A reusable helper
When many call sites need the same reading logic, collect failures into one place. This helper returns a map from input index to the error messages for that record.
public class DmlResultReader {
public static Map<Integer, List<String>> failures(List<Database.SaveResult> results) {
Map<Integer, List<String>> byIndex = new Map<Integer, List<String>>();
for (Integer i = 0; i < results.size(); i++) {
if (!results[i].isSuccess()) {
List<String> messages = new List<String>();
for (Database.Error err : results[i].getErrors()) {
messages.add(err.getMessage());
}
byIndex.put(i, messages);
}
}
return byIndex;
}
}Calling code can then check failures(results).isEmpty() to decide whether the whole batch succeeded, and look up an index to find what went wrong. UpsertResult and DeleteResult are separate classes and do not extend SaveResult, so you need an overload for each type.
Exercise
You call Database.upsert(accounts, Account.External_Id__c, false) with four accounts. The result list has four UpsertResult objects. Result 2 has isSuccess() equal to false. Which input account does it describe, what does getId() return for it, and why should you not read isCreated() for it?
Show answer
It describes the account at index 2 of the input list, because result order matches input order. For a failed upsert that would have created a record, getId() is null, so use the index to identify the account. isCreated() is not meaningful for a failed record because no insert or update took place. Check isSuccess() first and read isCreated() only for successes.
Exercise
A teammate writes Database.delete(oldRecords, false); on its own line and says the cleanup job never fails. What is the problem, and how would you fix it?
Show answer
With allOrNone set to false, delete errors are not thrown. They are reported only in the returned DeleteResult list, and the code discards that list, so failures go unnoticed. Assign the return value to a List<Database.DeleteResult>, loop over it, and for each result where isSuccess() is false, log or handle the entries from getErrors().