Sub topic 1
Writing Records in Apex: DML Operations
Prerequisites
Assume you know basic Apex syntax, collections, sObjects, fields, try/catch, and Salesforce transactions.
Writing records in Apex: the DML operations
Data manipulation language (DML) is how Apex creates, changes, and removes Salesforce records. The main operations are:
insertcreates records.updatechanges existing records.upsertinserts or updates records.deleteremoves records.undeleterestores records from the Recycle Bin.
DML accepts one sObject or a collection. Prefer collections when processing multiple records.
DML statements: the concise syntax
DML statements use short, direct syntax:
Account account = new Account(Name = 'Acme');
insert account;
account.Name = 'Acme Corporation';
update account;
delete account;
undelete account;An upsert uses the record ID by default. If the ID is present, Salesforce updates the record. If it is absent, Salesforce inserts it.
Account account = new Account(Name = 'Globex');
upsert account;A DML statement acts as an all-or-nothing operation for its input collection. If one record fails, the statement throws an exception and the operation rolls back.
Catching `DmlException` when a statement fails
A failed DML statement throws DmlException. Catch it when your code can report the error, choose another path, or perform cleanup.
try {
insert new Account(); // Name is required
} catch (DmlException e) {
System.debug('DML failed: ' + e.getMessage());
}Database class methods: the same operations as method calls
The Database class provides method versions of the same operations: Database.insert, Database.update, Database.upsert, Database.delete, and Database.undelete.
These methods return result objects and accept options such as allOrNone. With false, valid records can succeed even when other records fail.
List<Account> accounts = new List<Account>{
new Account(Name = 'Acme'),
new Account()
};
List<Database.SaveResult> results = Database.insert(accounts, false);
for (Database.SaveResult result : results) {
System.debug(result.isSuccess());
}Use statements for concise all-or-nothing work. Use Database methods when you need per-record results or partial success.
Exercise
Which approach should you choose when valid records must be saved even if another record fails?
Show answer
Use a Database method with allOrNone set to false.