Sub topic 1
Writing records in Apex: the DML operations
Prerequisites
This chapter assumes you can already do the following:
- Read and write basic Apex: classes, methods,
List,Set, andMap. - Work with SObjects and their fields, such as
Account.Name. - Use
try/catchblocks. - Recognize that Apex runs in a transaction, and that governor limits cap what one transaction can do.
You don't need to know the Database class yet. This chapter introduces it, and later chapters cover it in detail.
What DML is
Data Manipulation Language (DML) is the set of Apex operations that create, change, and remove records in the Salesforce database. SOQL reads records. DML writes them.
Apex offers six core write operations:
| Operation | What it does | Needs an `Id` on the record? |
|---|---|---|
| insert | Creates new records | No. Apex sets the `Id` after the insert. |
| update | Changes existing records | Yes |
| upsert | Updates a record if it exists, otherwise inserts it | Optional. It matches on `Id` or an external ID field. |
| delete | Moves records to the Recycle Bin | Yes |
| undelete | Restores records from the Recycle Bin | Yes |
| merge | Combines up to three records of the same type into one | Yes |
The merge operation works only on leads, contacts, and accounts. The other five work on any object that allows them.
Two ways to call the same operations
Apex gives you two syntaxes for most of these operations:
- DML statements are keywords in the language, such as
insert accounts;. - Database class methods are static methods on the
Databaseclass, such asDatabase.insert(accounts, false);.
Both call the same platform operations. Both count against the same governor limits. They differ in how they report failure and in how much control you get. This tutorial compares them.
The operations as statements
The statement form is the shortest. It takes a single SObject or a list of SObjects.
Account acct = new Account(Name = 'Acme');
insert acct;
System.debug('New Id: ' + acct.Id);
acct.Phone = '555-0100';
update acct;
delete acct;
// The Id is still set on the in-memory record, so we can restore it.
undelete acct;
System.debug('Restored: ' + acct.Id);Three behaviors in this example matter in practice:
- After
insert, Apex writes the newIdback to the same SObject variable. You can useacct.Idimmediately, for example to create child records. updatechanges only records that have anId. Callingupdateon a record without one throws an exception.deletedoes not destroy data at once. The record goes to the Recycle Bin, andundeletecan bring it back. Deleting a parent record also deletes its child records in master-detail relationships. The related child records are restored with the parent.
Working with lists
Every operation accepts a list. A list is how you handle many records in one call.
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 3; i++) {
accounts.add(new Account(Name = 'Batch account ' + i));
}
insert accounts;
for (Account a : accounts) {
a.Description = 'Created in a batch';
}
update accounts;This code runs two DML statements for three records. It does not run six. Remember this idea. The limits chapter returns to it.
Upsert and merge as statements
upsert decides between insert and update for each record. If you give it no field, it matches on the record Id. If the Id is set and exists, the record is updated. Otherwise the record is inserted.
Account existing = new Account(Name = 'Initech');
insert existing;
existing.Name = 'Initech Corp';
Account brandNew = new Account(Name = 'Hooli');
// One existing record (has an Id) and one new record (no Id).
upsert new List<Account>{ existing, brandNew };To match on your own key instead, you name an external ID field after the record or list, as in upsert accounts External_Id__c;. A later chapter covers this.
merge takes a master record and one or two duplicates. The duplicates are deleted, and their related records are reparented to the master.
Account master = new Account(Name = 'Globex');
Account duplicate = new Account(Name = 'Globex Inc');
insert new List<Account>{ master, duplicate };
merge master duplicate;The operations as Database methods
Each operation has a matching method on the Database class:
Database.insertDatabase.updateDatabase.upsertDatabase.deleteDatabase.undeleteDatabase.merge
The class adds two operations that have no statement form:
Database.convertLeadconverts a lead into an account, contact, and optionally an opportunity.Database.emptyRecycleBinpermanently removes records from the Recycle Bin.
Here is the earlier insert and update written with the methods:
Account acct = new Account(Name = 'Acme');
Database.SaveResult insertResult = Database.insert(acct);
System.debug('Success: ' + insertResult.isSuccess() + ', Id: ' + insertResult.getId());
acct.Phone = '555-0100';
Database.SaveResult updateResult = Database.update(acct);
System.debug('Updated: ' + updateResult.isSuccess());
Database.DeleteResult deleteResult = Database.delete(acct);
System.debug('Deleted: ' + deleteResult.isSuccess());Each method returns a result object. The type depends on the operation:
| Method | Returns |
|---|---|
| `Database.insert`, `Database.update` | `Database.SaveResult` (a list of them if you pass a list) |
| `Database.upsert` | `Database.UpsertResult` |
| `Database.delete` | `Database.DeleteResult` |
| `Database.undelete` | `Database.UndeleteResult` |
| `Database.merge` | `Database.MergeResult` |
A later chapter shows how to read these results.
The main difference: how failure is reported
The two forms differ most when a record fails to save. A record can fail because a required field is empty, a validation rule rejects it, or a trigger adds an error.
A DML statement is all-or-nothing. If any record fails, Apex throws a DmlException. The whole statement is rolled back, so none of the records in that statement are saved.
A Database method takes an optional second argument, allOrNone. It defaults to true, so with the default the method also throws a DmlException and saves nothing. If you pass false, the method saves the valid records, does not throw for record-level errors, and reports each failure in its result objects.
List<Account> accounts = new List<Account>{
new Account(Name = 'Valid account'),
new Account() // Name is required, so this record fails
};
// Statement form: throws, and neither record is saved.
try {
insert accounts;
} catch (DmlException e) {
System.debug('Statement failed: ' + e.getMessage());
}
// Method form with allOrNone = false: the valid record is saved.
List<Database.SaveResult> results = Database.insert(accounts, false);
System.debug('First saved: ' + results[0].isSuccess());
System.debug('Second saved: ' + results[1].isSuccess());The first call rolls back both records. The second call saves the valid account and reports the failure of the second.
Limits and cost
Statements and methods use the same governor limits. A single transaction can run at most 150 DML statements and process at most 10,000 records through DML. Database.insert(list, false) counts as one DML statement, just as insert list; does. Choosing the Database form does not buy you extra capacity.
What the rest of the tutorial covers
The next chapters take each part of this chapter in turn: statements and DmlException, then Database methods, allOrNone, and result objects. They end with limits, bulkification, and how to choose. Three smaller topics follow: Database.DMLOptions, external ID upserts, and savepoints.
Exercise
You call Database.update(accounts) on a list of 10 accounts, and one has a validation rule failure. You pass no second argument. What happens to the other 9 accounts, and what would you change to save them?
Show answer
The method defaults to allOrNone = true, so it throws a DmlException and none of the 10 accounts are saved. To save the 9 valid accounts, call Database.update(accounts, false) and check each returned SaveResult to find the failed record.
Exercise
A loop processes 200 contacts and runs update c; on each one inside the loop. Why is this a problem, and how do you fix it?
Show answer
The loop runs 200 DML statements, and a transaction allows only 150, so it fails with a governor limit exception. Add each changed contact to a List<Contact> inside the loop, then run one update contactList; after the loop. That uses one DML statement.