The Database Class and Partial Success
By the end of this lesson, you'll be able to:
- Use Database.insert with allOrNone set to false
- Check each result for success or failure without the whole operation throwing
- Explain when partial success is preferable to the default all-or-nothing behavior
Prerequisites: "Merge"
The default: all-or-nothing
List<Account> accounts = new List<Account>{
new Account(Name = 'Valid Account'),
new Account() // missing required Name — invalid
};
insert accounts; // throws a DmlException — NEITHER record gets saved
Plain insert on a List is all-or-nothing by default: if even one record in the batch fails validation, the entire batch is rolled back — even the perfectly valid Account never gets saved.
Database.insert with partial success
List<Account> accounts = new List<Account>{
new Account(Name = 'Valid Account'),
new Account() // still invalid
};
List<Database.SaveResult> results = Database.insert(accounts, false);
for (Database.SaveResult result : results) {
if (result.isSuccess()) {
System.debug('Saved: ' + result.getId());
} else {
System.debug('Failed: ' + result.getErrors()[0].getMessage());
}
}
Database.insert(accounts, false) — the false means "don't require all-or-nothing" — saves the valid Account and reports the failure for the invalid one, instead of losing both. results is a List<Database.SaveResult>, one entry per input record, in the same order, each reporting success or failure individually.
When to choose partial success
Partial success fits a batch import where a handful of bad rows shouldn't block the hundreds of good ones — process what's valid, and report the failures for someone to fix separately. All-or-nothing (the default, and Database.insert(accounts, true) explicitly) fits situations where related records must succeed together or not at all — like inserting an Opportunity alongside its required related records in one atomic operation.
Exercise
Given List<Account> accounts (some possibly invalid), use Database.insert with partial success, and debug how many succeeded vs failed.
Show hint
Loop over the results, counting isSuccess() true/false.
The Database Class and Partial Success Quiz
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
The plain insert/update/delete statements are all-or-nothing — one bad record fails the entire batch. Database.insert (and its siblings) can allow partial success instead, processing every valid record even if some fail.