Sub topic 3
Savepoints and the DML Statement Limit
Assume you know basic Apex syntax, sObject DML, try/catch, and governor limits. A savepoint lets one transaction return to an earlier database state. It does not create a separate transaction.
Savepoints and the DML Statement Limit
Database.setSavepoint() and Database.rollback() each consume a DML statement. A transaction also has a limit of five active savepoints. Set savepoints only around work that may need undoing.
Savepoint sp = Database.setSavepoint();
try {
Account a = new Account(Name = 'Temporary');
insert a;
Database.rollback(sp); // The insert is undone.
} catch (DmlException e) {
Database.rollback(sp);
}A rollback can undo database changes made after the savepoint. It does not undo every kind of program state.
State a Rollback Does Not Revert
| State | Reverted by rollback? |
|---|---|
| Inserted or updated database rows | Yes |
| Static variables and ordinary Apex variables | No |
| An sObject's in-memory `Id` value | No |
| External callouts or messages already sent | No |
After rolling back an inserted sObject, clear its Id before inserting that same object again.
Practical Patterns
Use a guarded block when several related operations must succeed together. Use Database.insert(records, false) when valid records should remain saved while invalid records are reported through SaveResult.
Do not assume catching an exception rolls back earlier DML. A caught exception leaves earlier successful work eligible for commit.
Callouts and Asynchronous Transactions
A callout after uncommitted DML can raise “uncommitted work pending.” Perform the callout before DML, or move the callout and database work into separate transactions.
Each future method, queueable execution, and batch execute call has its own transaction. Batch start, each execute scope, and finish run separately. Savepoints cannot cross these boundaries. A chained queueable also starts a new transaction.
Testing Rollback Behavior
Query before and after the rollback, then assert that the count returns to its original value.
@IsTest
private class RollbackTest {
@IsTest
static void rollbackRemovesRecord() {
Integer before = [SELECT COUNT() FROM Account];
Savepoint sp = Database.setSavepoint();
insert new Account(Name = 'Temporary');
Database.rollback(sp);
System.assertEquals(before, [SELECT COUNT() FROM Account]);
}
}Exercise
Which work should use partial-success DML instead of a savepoint?
Show answer
Use partial-success DML when valid records should be committed even though other records fail.