Sub topic 4
Database class methods: the same operations as method calls
This chapter assumes you can write basic Apex classes and methods, you know how SObjects and collections work, and you have used try/catch. You should also know that Apex runs in a transaction with governor limits. Earlier chapters covered DML statements and DmlException. Here you meet the second way to write records: static methods on the Database class.
What the Database class offers
Every DML statement has a matching method on the Database class. The method does the same work, but it takes its options as arguments and returns objects that describe what happened.
| DML statement | Database method | Return type (single or list) |
|---|---|---|
| `insert` | `Database.insert` | `Database.SaveResult` |
| `update` | `Database.update` | `Database.SaveResult` |
| `upsert` | `Database.upsert` | `Database.UpsertResult` |
| `delete` | `Database.delete` | `Database.DeleteResult` |
| `undelete` | `Database.undelete` | `Database.UndeleteResult` |
| `merge` | `Database.merge` | `Database.MergeResult` |
Two further methods have no statement equivalent. Database.convertLead converts leads and returns Database.LeadConvertResult. Database.emptyRecycleBin permanently removes records from the Recycle Bin and returns Database.EmptyRecycleBinResult.
With a single record, the method returns one result object. With a list, it returns a List of result objects, one per input record, in the same order as the input.
The same operation, written both ways
This example inserts one account with a statement and one with the method.
Account viaStatement = new Account(Name = 'Statement Co');
insert viaStatement;
Account viaMethod = new Account(Name = 'Method Co');
Database.SaveResult sr = Database.insert(viaMethod);
System.debug('Statement id: ' + viaStatement.Id);
System.debug('Method id: ' + viaMethod.Id);
System.debug('Method succeeded: ' + sr.isSuccess());Both calls assign an Id to the record you passed in. Both calls fire the same triggers, validation rules, and workflow automation. Both count against the same governor limits. The difference lies in how the call reports its outcome and how much control you have over failures.
The allOrNone parameter and its default
Most overloads of the Database methods accept a Boolean named allOrNone. If you leave it out, it defaults to true. With true, the method behaves like the statement: if any record fails, the whole operation rolls back, and the method throws a DmlException.
List<Account> accounts = new List<Account>{
new Account(Name = 'Valid'),
new Account() // missing required Name
};
try {
Database.insert(accounts); // allOrNone defaults to true
} catch (DmlException e) {
System.debug('Whole call failed: ' + e.getMessage());
}Calling Database.insert(accounts) with no second argument is therefore not safer than insert accounts;. You get the benefit only when you pass false:
List<Database.SaveResult> results = Database.insert(accounts, false);With false, valid records are saved and failed records are reported in the results. The next chapter covers this behavior in detail. For now, remember that allOrNone is the switch that decides between "throw and roll back" and "report and continue".
Overloads you will use
Each method comes in several overloads. The ones you will use most are listed here.
Database.insert(SObject record)andDatabase.insert(List<SObject> records): defaultallOrNoneoftrue.Database.insert(SObject record, Boolean allOrNone)andDatabase.insert(List<SObject> records, Boolean allOrNone): you choose the behavior.Database.insert(SObject record, Database.DMLOptions options)and the list equivalent: you pass aDatabase.DMLOptionsobject, which can also setallOrNonethroughoptAllOrNone.Database.updatehas the same overload set asinsert.Database.upsert(List<SObject> records, Schema.SObjectField externalIdField, Boolean allOrNone): the optional field token chooses the matching key. Without it, upsert matches onId.Database.deleteandDatabase.undeleteaccept an SObject, a list of SObjects, a single recordId, or a list ofIdvalues, each with an optionalallOrNone.
Delete and undelete accept IDs directly, which saves you from building throwaway SObject instances. This class restores records from the Recycle Bin and counts how many came back:
public class AccountRestorer {
public static Integer restore(List<Id> accountIds) {
List<Database.UndeleteResult> results =
Database.undelete(accountIds, false);
Integer restored = 0;
for (Database.UndeleteResult ur : results) {
if (ur.isSuccess()) {
restored++;
}
}
return restored;
}
}If one ID is not in the Recycle Bin, the method does not throw. That record's result has isSuccess() equal to false, and the rest are restored.
What a result object tells you
A result object is a small record of what happened to one input record. The type depends on the operation, but they share the same core methods.
| Method | Meaning |
|---|---|
| `isSuccess()` | `true` if the record was processed without error |
| `getId()` | The record's ID. For a failed insert it is `null` |
| `getErrors()` | A list of `Database.Error`, empty on success |
UpsertResult adds isCreated(), which tells you whether the record was inserted or updated. The later chapters on result objects and error inspection cover these classes in full. This chapter only needs the idea that the method hands the failure information to you as data, instead of throwing it.
How the two forms flow
The diagram shows what happens after you choose a form and what allOrNone does to the outcome.
Errors that still throw
Passing false removes record-level DmlException errors. It does not make the call safe from everything. These still throw or stop execution:
- Governor limit violations. Exceeding the DML statement or DML row limit raises a
LimitException, which you cannot catch. - Argument problems that make the call invalid, such as passing a
nulllist or mixing in a record that is not valid for the operation, for example updating a record with noId. A record with noIdin an update call is often reported as a per-record error in the results, but a structurally invalid call throws. - Errors raised by your own code, for example in a trigger that calls
addError. Those show up as per-record errors in the results whenallOrNoneisfalse. An uncaught exception thrown by Apex code in a trigger still propagates.
The practical rule is to keep your try/catch around Database method calls when you care about unexpected failures. Use the result list for expected, record-level failures.
Statements versus methods: the working differences
- Return value: a statement returns nothing. A method returns result objects.
- Failure style: a statement always fails the whole operation with an exception. A method can do the same (default) or report per record.
- Options: a statement has no way to pass options. A method takes
allOrNone,DMLOptions, and an external ID field for upsert. - Capabilities: only methods give you
convertLeadandemptyRecycleBin. Header-style options such as field truncation needDMLOptions. - Limits and automation: identical. Triggers, flows, and governor limits treat both forms the same way.
Because the limits are identical, switching a statement to a method never saves you a DML statement. A later chapter covers this in depth.
Common mistakes
- Calling
Database.insert(records)and expecting no exception. The default isallOrNone = true. - Ignoring the returned list when
allOrNoneisfalse. Failures then go unnoticed, because nothing throws. - Assuming the result list is shorter when records fail. It always has one entry per input record, in input order.
- Using the returned list after a catch block. If the call threw, the assignment never happened, so the variable still holds its earlier value, often
null.
Exercise
A developer writes List<Database.SaveResult> res = Database.update(contacts); and expects bad records to be skipped while good ones are saved. One contact fails a validation rule. What actually happens, and what single change gives the intended behavior?
Show answer
Because allOrNone defaults to true, the call rolls back every contact and throws a DmlException, so res is never assigned. Passing false as the second argument, Database.update(contacts, false), saves the valid contacts and returns a SaveResult for each one, with the failed contact's result reporting isSuccess() as false.
Exercise
You call Database.delete(idList, false) with 10 IDs, and 2 of them cannot be deleted. How many DeleteResult objects are returned, and how do you find the failures?
Show answer
Ten, one per input ID in the same order. Loop over the list and check isSuccess(). For results where it is false, call getErrors() to read the status code and message.