Sub topic 2
DML statements: the concise syntax
This chapter covers the DML statements Apex provides for writing records. It assumes you know basic Apex syntax and collections, you can read SOQL queries, and you understand that Apex runs inside a transaction with governor limits. Error handling is covered in the next chapter, and the Database class methods in the one after it.
What a DML statement is
DML (Data Manipulation Language) is the part of Apex that creates, changes, and removes records. A DML statement is a keyword followed by a record or a list of records. The statements are insert, update, upsert, delete, undelete, and merge.
Account acc = new Account(Name = 'Acme');
insert acc;There are no parentheses and no return value. The statement either succeeds or throws an exception. This brevity is the main reason to use statements.
| Statement | What it does | Record must have an Id? |
|---|---|---|
| `insert` | Creates new records | No. It must not have one |
| `update` | Changes existing records | Yes |
| `upsert` | Inserts or updates, depending on whether a match exists | Optional |
| `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 |
Insert
insert accepts a single SObject or a list. After a successful insert, Apex writes the new Id into the in-memory record. You can use that Id immediately, for example to create child records.
Account acc = new Account(Name = 'Acme');
insert acc;
System.debug('New account Id: ' + acc.Id);
List<Contact> contacts = new List<Contact>{
new Contact(LastName = 'Smith', AccountId = acc.Id),
new Contact(LastName = 'Jones', AccountId = acc.Id)
};
insert contacts;The Id is populated on the same object instance you passed in. This works because SObjects are passed by reference.
Inserting a record that already has an Id fails. Apex does not let you set the Id on a new row. This is a common mistake when you reuse a record variable:
Account acc = new Account(Name = 'Acme');
insert acc;
insert acc; // fails: the record already has an IdUpdate
update needs the Id of each record. The usual pattern is to query, change fields in memory, and then update:
List<Account> accounts = [SELECT Id, Rating FROM Account WHERE Name LIKE 'Acme%'];
for (Account a : accounts) {
a.Rating = 'Hot';
}
update accounts;You do not have to query a record to update it. If you know the Id, you can build a new SObject that sets only the Id and the fields you want to change:
Id accountId = [SELECT Id FROM Account LIMIT 1].Id;
update new Account(Id = accountId, Phone = '555-0100');Apex sends only the fields you set. Fields you did not touch keep their stored values. This is cheaper than querying first.
There is one trap. Reading a field you did not query, such as acc.Industry when your SOQL selected only Id, throws a System.SObjectException. Setting a field on such an object is fine.
Delete and undelete
delete accepts a record, a list, or an Id. It moves records to the Recycle Bin, which is a soft delete. Child records that cascade-delete go with them.
List<Contact> old = [SELECT Id FROM Contact WHERE LastName = 'Smith'];
delete old;To restore records, query them with ALL ROWS, which includes deleted records, and pass them to undelete:
List<Contact> restored = [
SELECT Id FROM Contact
WHERE LastName = 'Smith' AND IsDeleted = true
ALL ROWS
];
undelete restored;undelete only works on records still in the Recycle Bin. Once the retention period passes or someone empties the bin, the records are gone. Records removed with a hard delete never reach the bin.
Upsert
upsert decides per record whether to insert or update. Without a field named, Apex matches on Id. A record with an Id is updated, and one without is inserted.
Account existing = [SELECT Id FROM Account LIMIT 1];
existing.Description = 'Updated by upsert';
List<Account> batch = new List<Account>{
existing,
new Account(Name = 'Brand New Co')
};
upsert batch;You can also name an external ID field so upsert matches on your own key. That form is covered later in this tutorial, because the Database.upsert result objects make it much more useful.
Merge
merge takes a master record and up to two duplicates. It deletes the duplicates and reassigns their related records to the master. It works only for leads, contacts, accounts, and cases.
Account master = [SELECT Id FROM Account WHERE Name = 'Acme' LIMIT 1];
Account dupe = [SELECT Id FROM Account WHERE Name = 'Acme Inc' LIMIT 1];
merge master dupe;How a statement behaves
Every DML statement follows the same rule when you pass it a list: it is all-or-nothing. If any record in the list fails, the statement throws a DmlException and none of the records from that statement are saved. The mechanics of catching that exception are the subject of the next chapter.
Do not use the empty block above. The correct diagram follows.
Two details in the diagram matter in practice.
- Atomic per statement. One bad row in a list of 200 means zero rows saved. If that is not what you want, you need the
Databasemethods. - Atomic per transaction only when uncaught. If you catch the exception, Apex does not undo DML from earlier statements. They commit when the transaction ends. If you need to undo them, use a savepoint, which a later chapter covers.
What can make a statement fail
A statement fails for any of these reasons, and each one fails the whole list:
- A required field is missing, as in
new Account()with noName. - A validation rule rejects the record.
- A value is too long for its field, such as a 300-character
Name. - A trigger or flow on the object throws an error or calls
addError. - The user lacks object or field permissions in a context that enforces them.
- You called
updateordeleteon a record with no Id. - You called
inserton a record that already has an Id.
Triggers and flows run as part of the statement. The statement does not return until they finish, and an error in any of them fails the statement.
Lists with mixed record types
A list declared as List<SObject> can hold records of different types, and one statement can save them:
List<SObject> mixed = new List<SObject>{
new Account(Name = 'Mixed Co'),
new Opportunity(Name = 'Big Deal', StageName = 'Prospecting', CloseDate = Date.today().addDays(30))
};
insert mixed;Apex processes such a list in chunks of consecutive same-type records. If your list alternates types, such as Account, Opportunity, Account, Opportunity, the number of chunks grows. A single statement that needs more than 10 chunks fails with a "Cannot have more than 10 chunks in a single operation" error. Sort the list by type before the statement, or use one list per type.
Limits in brief
Each DML statement counts as one DML statement against the per-transaction limit, whatever the list size. Each record in the list counts toward the total rows-processed limit. In synchronous Apex the limits are 150 statements and 10,000 rows. Putting a statement inside a loop spends the statement limit quickly. A later chapter in this tutorial covers limits and bulkification in detail. For now, follow this habit: collect records in a list inside the loop and run one statement after it.
List<Contact> toUpdate = new List<Contact>();
for (Contact c : [SELECT Id, Title FROM Contact WHERE Title = null LIMIT 200]) {
c.Title = 'Unknown';
toUpdate.add(c);
}
update toUpdate;An empty list is safe. Running update toUpdate; on an empty list does nothing and does not throw. It does still count as a DML statement, so you can guard it with if (!toUpdate.isEmpty()) when you are close to a limit.
Strengths and limits of the statement syntax
Statements are short and easy to read, and they fail loudly. The drawback is that the failure is coarse. You get one exception for the whole list, with no clean way to keep the good records. When that matters, the Database methods are the tool.
Summary of habits
- Run each statement once on a collection, outside any loop.
- Never set an Id before
insert. - Make sure each record has an Id before
updateordelete. - Check what you queried before reading fields from a record you plan to update.
- Expect a list to save in full or not at all.
Exercise
A method runs insert new Account(Name = 'First');, then wraps insert new List<Account>{ new Account(Name = 'Second'), new Account() }; in a try/catch that swallows the exception, and then returns normally. Which accounts exist after the transaction completes, and why?
Show answer
Only 'First' exists. The second statement fails because the second record has no Name, so the whole list of that statement is rejected and 'Second' is not saved. The first statement already succeeded, and because the exception was caught the transaction is not rolled back, so 'First' is committed when the transaction ends.
Exercise
Why does this code fail, and how do you fix it? Account acc = new Account(Name = 'Acme'); insert acc; acc.Name = 'Acme Corp'; insert acc;
Show answer
The second insert fails because acc already has an Id from the first insert, and an insert cannot be given an Id. Change the second statement to update acc;.