Sub topic 11
Choosing between statements and Database methods
This chapter assumes you know basic Apex syntax, try/catch, SObjects, and that Apex runs in transactions with governor limits. It also assumes you have seen DmlException, the allOrNone parameter, and the result objects from earlier chapters.
The two approaches in one view
Both approaches run the same operations. They count against the same DML limits. The difference is how a failure reaches your code.
| Question | DML statement | Database method |
|---|---|---|
| Syntax | `insert accounts;` | `Database.insert(accounts, false);` |
| Default on a record error | Throws `DmlException`, rolls back the whole operation | Same, unless `allOrNone` is `false` |
| Partial success | Not available | Set `allOrNone` to `false` |
| Return value | None | One result object per input record, in input order |
| Options such as `Database.DMLOptions` | Not available | Available |
Note that Database.insert(accounts) with no second argument behaves like the statement, because allOrNone defaults to true.
A decision flow
Ask one question first: should one bad record stop the whole save?
When a statement is the better choice
Use a statement when the records belong together and a partial save would leave bad data. Examples are an order and its line items, or a parent and the children that depend on it.
- The code is shorter and easier to read.
- A failure stops execution at that line, so later code never runs against half-saved data.
- If no code can fix the problem, let the exception propagate. The platform rolls back the transaction for you.
// An order and its lines must be saved together.
Order__c order = new Order__c(Name = 'Order 1');
insert order;
List<Order_Line__c> lines = new List<Order_Line__c>();
for (Integer i = 1; i <= 3; i++) {
lines.add(new Order_Line__c(Order__c = order.Id, Quantity__c = i));
}
insert lines; // any failure throws and the transaction is rolled backOrder__c and Order_Line__c are hypothetical custom objects used for illustration.
When a Database method is the better choice
Use a Database method when records are independent and you want the valid ones saved. Typical cases are data loads, integrations that receive a batch from another system, and cleanup jobs.
- Set
allOrNonetofalseso valid records are saved. - Read each result to log, report, or retry the failures.
- Use
Database.DMLOptionsor an external ID upsert when you need those features.
List<Contact> contacts = new List<Contact>{
new Contact(LastName = 'Smith'),
new Contact() // LastName is required, so this record fails
};
List<Database.SaveResult> results = Database.insert(contacts, false);
List<String> failures = new List<String>();
for (Integer i = 0; i < results.size(); i++) {
if (!results[i].isSuccess()) {
failures.add('Row ' + i + ': ' + results[i].getErrors()[0].getMessage());
}
}
System.debug(failures);Common errors
- Ignoring the results. With
allOrNoneset tofalse, nothing throws. If you do not read the results, failures go unnoticed. - Assuming a Database method always avoids exceptions. It only skips the record-level
DmlException. Other errors can still throw, so a surrounding try/catch is still reasonable. - Using a Database method inside a loop. Each call counts as a DML statement. Both approaches need collections, as covered in the bulkification chapter.
- Expecting partial rollback in a statement. A statement undoes the whole operation, not only the failed record.
Quick rules
- Records must succeed together: statement.
- Valid records should survive bad ones: Database method with
allOrNoneset tofalse. - You need field truncation or per-record error reporting: Database method.
- You are unsure: start with the statement, and switch when a real requirement calls for partial success.
Exercise
A nightly job receives 200 contact records from an external system. Some will fail validation, and the business wants the valid ones saved and the failures reported. Which approach should you use, and what must the code do with the return value?
Show answer
Use Database.insert(contacts, false). The code must loop over the returned List<Database.SaveResult>, check isSuccess() for each, and record the errors from getErrors() for the failed ones. Results are in the same order as the input, so the index identifies the failing record.
Exercise
A developer writes Database.update(accounts); and expects bad records to be skipped. Why does one bad record still stop the save?
Show answer
The allOrNone parameter defaults to true when you leave it out. The call then behaves like an update statement, so any record error fails the whole operation. Passing false as the second argument enables partial success.