Sub topic 14
Savepoints and Rollback Around DML
This chapter assumes you can write Apex try/catch blocks, know that a transaction is one execution context with governor limits, and have used insert and Database.insert. It covers how to undo DML you have already run in the same transaction.
Why you might need to undo DML
A DML statement that fails rolls back only its own work. Statements that succeeded earlier in the transaction stay pending until the transaction ends. If your code later decides the whole unit of work is invalid, you have to undo the earlier statements yourself.
Typical cases:
- A callout or validation step fails after you have already inserted parent records.
- You catch an exception and want to continue, but without leaving half-finished data behind.
- A partial-success
Database.insertsaved some rows, and a later step shows those rows should not exist.
How savepoints work
Database.setSavepoint() returns a Savepoint object that marks a point in the transaction. Database.rollback(sp) restores the database state to that point. All DML run after the savepoint is undone, whether it came from statements or Database methods.
Savepoint sp = Database.setSavepoint();
try {
insert new Account(Name = 'Acme');
insert new Contact(LastName = 'Smith');
// Further logic may decide the work must be undone
throw new CalloutException('Simulated downstream failure');
} catch (Exception e) {
Database.rollback(sp);
System.debug('Rolled back: ' + e.getMessage());
}Both inserts succeed, then the exception fires. The catch block rolls back to the savepoint, so neither the account nor the contact is saved.
What rollback does and does not undo
A rollback restores database records. It does not reset everything.
- Records inserted before the rollback no longer exist. Their
Idvalues stay on your in-memory SObject variables, but the Ids point at nothing. Do not reuse those variables in a later insert without clearing the Id. - Governor limit usage is not restored. The DML statements and DML rows you already consumed still count.
- Callouts that already completed are not undone. External systems keep whatever you sent.
- Emails sent, and other non-database side effects, are not reversed.
Savepoint sp = Database.setSavepoint();
Account acc = new Account(Name = 'Acme');
insert acc;
Database.rollback(sp);
System.debug(acc.Id != null); // true: the variable keeps its Id
System.debug([SELECT COUNT() FROM Account WHERE Name = 'Acme']); // the record is gone
System.debug(Limits.getDmlStatements()); // the insert still countsSavepoint rules and gotchas
- Each savepoint and rollback counts as a DML statement against the per-transaction limit of 150.
- Rolling back to an earlier savepoint invalidates later ones. If you create
sp1, thensp2, and roll back tosp1, usingsp2throws a runtime error. - Savepoints belong to one transaction. You cannot carry a
Savepointacross an asynchronous boundary. - Mixed DML and callouts need care. Setting a savepoint or rolling back does not make a callout safe after uncommitted DML. The "uncommitted work pending" restriction on callouts still applies.
- Unhandled exceptions already roll back everything. If the transaction ends with an uncaught exception, Salesforce undoes all its DML. You need a savepoint only when you catch the exception and keep running.
Choosing where savepoints fit
Use a savepoint when you catch an error and want to continue with a clean state. For example, a method that creates several related records can set a savepoint at its start and roll back in its catch block, then return an error message to the caller instead of leaving partial data.
If you do not catch the exception, you do not need a savepoint. If you only want to skip bad records in a single DML call, allOrNone = false is simpler. Savepoints are for undoing work across several statements.
Exercise
Your code inserts an Account, then inserts related Contacts with Database.insert(contacts, false). Afterward, you find that any failed Contact means the Account should not exist. You catch no exception because partial success does not throw. How do you undo the Account insert?
Show answer
Call Database.setSavepoint() before the Account insert. After the Contact insert, check each SaveResult with isSuccess(). If any result failed, call Database.rollback(sp). The rollback removes the Account and any Contacts that did save. Savepoint and rollback calls count toward the DML statement limit, and the in-memory Account keeps its stale Id.