Sub topic 1
Apex Transactions, Savepoints, and Rollback
Prerequisites
This chapter assumes you know basic Apex syntax, sObjects, DML statements such as insert and update, try/catch, DmlException, and the idea of governor limits.
What an Apex transaction is
An Apex transaction is one unit of work. It includes the Apex code that runs, the DML statements it performs, and related automation such as triggers and flows. Salesforce commits the transaction when execution finishes successfully. A commit makes the database changes permanent.
If the transaction fails with an unhandled exception, Salesforce rolls back its database changes. A rollback removes DML work made during that transaction.
Where a transaction starts and ends
A transaction starts at an execution entry point, such as an anonymous Apex request, a trigger invocation, a synchronous controller action, or an asynchronous job. It ends when that execution completes, succeeds, or fails.
A single request can invoke several triggers and related operations, but they share the same transaction. A queueable job and its enqueued follow-up job run in separate transactions.
What happens when an exception is not handled
An exception that leaves the entry-point code unhandled causes the transaction to fail. Salesforce rolls back DML performed earlier in the same transaction, including successful statements.
insert new Account(Name = 'First');
insert new Account(); // Name is required; this throws DmlException
// The first Account is also rolled back.All-or-none behavior of a single DML statement
A normal DML statement is all-or-none. If one record in the statement fails, Salesforce rolls back every record in that statement.
| Operation | One record fails | Other records in that statement |
|---|---|---|
| `insert records` | The statement fails | Rolled back |
This behavior applies to the statement, not necessarily to earlier work. If the exception is caught, earlier work can remain committed when the transaction ends.
Partial success with Database.insert and allOrNone
Use Database.insert(records, false) when valid records should save even if other records fail. The method returns a Database.SaveResult for each input record.
List<Account> accounts = new List<Account>{
new Account(Name = 'Good'),
new Account()
};
Database.SaveResult[] results = Database.insert(accounts, false);
for (Database.SaveResult result : results) {
if (!result.isSuccess()) {
for (Database.Error error : result.getErrors()) {
System.debug(error.getMessage());
}
}
}The successful record is saved if the transaction later completes normally. An unhandled exception after this call still rolls back the whole transaction.
Exercise
Two records are inserted with Database.insert(records, false). One succeeds, then an unhandled exception occurs later. What remains in the database?
Show answer
Neither record remains, because the unhandled exception rolls back the entire transaction.