Sub topic 11
Choosing between statements and Database methods
This chapter assumes you can write basic Apex classes and methods, work with SObjects and collections, use try/catch, and know that Apex runs in transactions under governor limits. Earlier chapters covered DML statements, DmlException, the Database methods, allOrNone, and result objects. Here you will use that material to decide which form fits a given requirement.
The short answer
Both forms perform the same operations. They call the same platform code, validate the same rules, fire the same triggers, and count against the same governor limits. The practical differences are in error handling and in the options you can pass.
| Aspect | DML statement (`insert accounts;`) | Database method (`Database.insert(accounts, false)`) |
|---|---|---|
| Default on failure | All-or-nothing. Throws `DmlException` and rolls back the whole operation. | `allOrNone` defaults to `true`, which also throws. Pass `false` to allow partial success. |
| Partial success | Not available. | Available with `allOrNone = false`. |
| Return value | None. | One result object per input record, in input order. |
| Record-level errors | Read from the exception. | Read from `Database.Error` objects in each result. |
| Extra options | None. | `Database.DMLOptions`, external ID field tokens for upsert. |
| Code size | Small. | Larger, because you inspect the results. |
The row about defaults matters. Calling Database.insert(accounts) with no second argument behaves like the statement, because allOrNone is true. The method only behaves differently when you pass false or a DMLOptions object that sets optAllOrNone to false.
Decision flow
When a DML statement is the better choice
Use a statement when a failure should stop the work. This is the right default for most code, for these reasons.
- The records belong together. An order and its line items make no sense if only some are saved. The exception rolls back the whole operation, and the caller sees the failure.
- You cannot meaningfully continue. If a failed save means the rest of the method has nothing valid to work with, throwing is simpler than checking flags.
- Readability matters. One line states the intent. Fewer lines means fewer places for mistakes.
- A caller or trigger should see the error. In a trigger, you can call
addErroron a record to report a validation problem. For a failed DML in a service class, letting the exception propagate keeps the error visible instead of hiding it.
public with sharing class OrderService {
public static void saveOrder(Account acct, List<Contact> contacts) {
insert acct;
for (Contact c : contacts) {
c.AccountId = acct.Id;
}
insert contacts;
}
}If the contact insert fails, the exception propagates out of saveOrder. When the transaction ends with an unhandled exception, the platform rolls back all of its changes, including the account. If a caller catches the exception and continues, the account insert is not undone automatically. In that case, use a savepoint, as described later in this chapter.
When a Database method is the better choice
Use a Database method when records are independent and you want the valid ones saved.
- Data loads and integrations. One bad row in a batch of 200 should not block the other 199. You collect the failures and report them.
- You need per-record error detail.
Database.Errorgives yougetStatusCode(),getMessage(), andgetFields()for each failing record. - You need
Database.DMLOptions. Field truncation and similar behaviors are only available through the method form. - You need an upsert keyed on an external ID field.
Database.upsert(records, Account.External_Id__c, false)takes a field token. The statement form,upsert records Account.External_Id__c;, also accepts one, but only the method gives youUpsertResultandisCreated(). - You need the result for later logic. For example, you want the new IDs of the records that succeeded and the input records that failed, so you can retry or log them.
Here is a pattern that separates successes from failures without losing the link to the input:
public with sharing class AccountLoader {
public class LoadSummary {
public List<Account> saved = new List<Account>();
public List<Account> rejected = new List<Account>();
public List<String> messages = new List<String>();
}
public static LoadSummary load(List<Account> accounts) {
LoadSummary summary = new LoadSummary();
List<Database.SaveResult> results = Database.insert(accounts, false);
for (Integer i = 0; i < results.size(); i++) {
if (results[i].isSuccess()) {
summary.saved.add(accounts[i]);
} else {
summary.rejected.add(accounts[i]);
for (Database.Error err : results[i].getErrors()) {
summary.messages.add(
'Row ' + i + ': ' + err.getStatusCode() + ' - ' + err.getMessage()
);
}
}
}
return summary;
}
}The index i works because the result list is in the same order as the input list. That is the reason you do not need to search for a record by ID.
Common mistakes
Ignoring the results
Database.insert(accounts, false) does not throw for record-level errors. If you call it and discard the return value, failures disappear without a trace. If you pass false, you take on the job of checking every result.
// Wrong: failures are silently ignored
Database.insert(accounts, false);
// Right: capture and inspect
List<Database.SaveResult> results = Database.insert(accounts, false);Expecting a try/catch to catch partial failures
With allOrNone = false, a catch (DmlException e) block will not run for record-level errors. It can still run for other problems, such as a failure that applies to the whole call. Treat the result list as the main error channel.
Using the method form out of habit
Writing Database.insert(records, false) everywhere, then not handling the results, is worse than a statement. It makes the code longer and hides errors. Choose partial success only when the requirement calls for it.
Moving DML into loops to get per-record handling
Developers sometimes write a statement inside a for loop and a try/catch around each one, so one record's failure does not affect the rest. This works at small scale but uses one DML statement per record and quickly reaches the limit of 150 DML statements per transaction. The Database method with allOrNone = false does the same job in one call. Always pass a collection.
// Wrong: one DML statement per record
for (Account a : accounts) {
try {
insert a;
} catch (DmlException e) {
System.debug(e.getMessage());
}
}
// Right: one DML call for the whole list
List<Database.SaveResult> results = Database.insert(accounts, false);Assuming partial success avoids rollback problems
Partial success saves the good records. It does not undo them if a later step in the same transaction fails. If later logic can decide that the saved work must be undone, set a savepoint before the DML and call Database.rollback(sp) afterward.
What does not change between the two
Choosing a form never changes limits. Each DML call, whether a statement or a method, counts as one DML statement against the limit of 150 per transaction. The limit on rows is 10,000 records processed by DML per transaction. Passing a list of 200 records uses one statement and 200 rows. Because the limits are equal, bulkification is the lever that matters, not the form you pick.
Triggers, validation rules, and workflow behavior are also the same. Records that fail validation under a statement also fail under a Database method. The only difference is whether that failure aborts the call.
Practical guidance
Apply these rules in order.
- If every record must succeed together, use a statement, or
Database.insert(records)with the defaultallOrNone. - If good records should be saved despite bad ones, use a Database method with
allOrNone = falseand inspect every result. - If you need
DMLOptionsorUpsertResult.isCreated(), use the Database method. - Always pass collections, never single records in a loop.
- If later steps may require undoing earlier DML in the same transaction, add a savepoint.
Also consider who consumes the error. If a user clicks a button and needs a clear message, convert the first Database.Error into a message. If a scheduled job runs unattended, write failures to a log object or a custom error record so someone can review them.
Exercise
A nightly integration inserts up to 200 Contact records per call from an external file. Some rows have invalid email addresses. The business wants the valid contacts saved and a list of the rejected rows. Which form do you use, and how do you find which rows were rejected?
Show answer
Use Database.insert(contacts, false) so one invalid row does not roll back the rest. Store the returned List<Database.SaveResult>. The results are in the same order as the input list, so loop with an index i. When results[i].isSuccess() is false, contacts[i] is the rejected row, and results[i].getErrors() gives the status code, message, and fields for it. A plain insert would throw a DmlException and save none of the contacts.
Exercise
A developer writes Database.update(opps, false); and never reads the return value. A few opportunities fail a validation rule. What happens, and how should the code change?
Show answer
The valid opportunities are saved, the failing ones are not, and no exception is thrown, so the failures go unnoticed. The code should assign the result to a List<Database.SaveResult>, loop over it, and handle each result where isSuccess() is false, for example by logging getErrors(). If the failures should not be tolerated, use update opps; or Database.update(opps) and let the DmlException surface.