Sub topic 8
Setting a savepoint
This chapter assumes you can write basic Apex classes and methods, run DML statements such as insert and update, and use try/catch with DmlException. It also assumes you know that Apex enforces governor limits. The previous chapters covered what a transaction is and why a caught exception does not undo earlier DML. This chapter covers the tool that fixes that: the savepoint.
What a savepoint is
A savepoint is a marker for a position inside the current transaction. You create one with Database.setSavepoint(). The call returns a Savepoint object. Later in the same transaction, you can pass that object to Database.rollback() to undo the database changes made after the marker. Changes made before the marker stay in place.
A savepoint does not commit anything. It does not start a new transaction. It does not change what the platform does at the end of the request. It only records "the database looked like this at this point."
Savepoint sp = Database.setSavepoint();Savepoint is a built-in type in the System namespace. It has no fields or methods you can use. Treat it as an opaque token that you hand back to Database.rollback.
Why you need one
Without a savepoint, your options for undoing DML are limited. An unhandled exception rolls back the whole transaction, but that is all-or-nothing. If you catch the exception, nothing is undone, as you saw in the previous chapter. A savepoint gives you a middle path. You can try a group of related changes, catch a failure, and discard only that group while the rest of the transaction continues.
This example sets a savepoint before inserting a parent and a child record. If either insert fails, it undoes both.
Savepoint sp = Database.setSavepoint();
try {
Account acct = new Account(Name = 'Acme Test');
insert acct;
Contact c = new Contact(LastName = 'Doe', AccountId = acct.Id);
insert c;
} catch (DmlException e) {
Database.rollback(sp);
System.debug('Rolled back: ' + e.getMessage());
}If the Contact insert fails, the Account insert has already succeeded. Catching the exception does not remove it. Database.rollback(sp) does. The next chapter covers rollback in detail. Here the focus is on where and how you set the savepoint.
Where to set the marker
The savepoint captures the database state at the moment you call setSavepoint. Set it before the first operation you might want to undo, and after any work you want to keep.
insert new Account(Name = 'Keep me'); // outside the guarded block
Savepoint sp = Database.setSavepoint(); // marker goes here
insert new Account(Name = 'Maybe undo me');
Database.rollback(sp); // only the second account is undoneIf you set the savepoint too late, the work you wanted to protect falls before the marker and cannot be undone. If you set it too early, a rollback also discards work you meant to keep.
The diagram below shows the order of events for the example above.
A savepoint exists only inside one transaction
A savepoint is only meaningful in the transaction that created it. It is a local reference, not stored data. Three consequences follow.
- You cannot save a savepoint and use it in a later request. When the transaction ends, the savepoint is gone.
- You cannot hand a savepoint to asynchronous Apex, such as a queueable job, and roll back across that boundary. The async job runs in its own transaction.
- You can pass a savepoint between methods in the same transaction, store it in a variable, or return it from a method. All of these work.
This helper pattern sets the marker in one place and lets the caller decide what to do with it:
public class OrderService {
public static Savepoint begin() {
return Database.setSavepoint();
}
public static void createOrder(String accountName) {
Savepoint sp = begin();
try {
Account a = new Account(Name = accountName);
insert a;
insert new Contact(LastName = 'Buyer', AccountId = a.Id);
} catch (DmlException e) {
Database.rollback(sp);
throw e;
}
}
}The method rolls back its own work and rethrows the exception. The caller still sees the failure, and the database is clean. Without the rethrow, the caller would assume the order was created.
Multiple savepoints
You can set more than one savepoint in a transaction. Each one marks a later position than the one before it. Rolling back to an earlier savepoint also discards everything after it, including the later savepoints, which then become invalid. Using an invalid savepoint raises a runtime error. A later chapter, "Why later savepoints become invalid", covers this. For now, remember two rules:
- Set savepoints in the order you would unwind them.
- Roll back to the most recent savepoint you still need, not an older one, unless you intend to discard everything after the older one.
Setting a savepoint costs a DML statement
Each call to Database.setSavepoint() counts as one DML statement against the governor limit. The limit is 150 DML statements per transaction. You can check this directly with the Limits class.
Integer before = Limits.getDmlStatements();
Savepoint sp = Database.setSavepoint();
Integer after = Limits.getDmlStatements();
System.debug('Savepoint cost: ' + (after - before)); // 1A Database.rollback call also counts as a DML statement, so a set-and-rollback pair costs two. This matters in loops. A savepoint inside a loop over 200 records would exceed the limit and throw a System.LimitException, which you cannot catch. If you need per-record isolation, use Database.insert(records, false). It saves valid records and reports the failed ones, and it costs one statement for the whole list. The chapter on partial success covers it.
// Anti-pattern: one savepoint per record
for (Account a : accounts) {
Savepoint sp = Database.setSavepoint(); // costs one DML statement per iteration
// ...
}The costs are covered fully in "Savepoints and the DML statement limit". The practical rule for now is to set a savepoint per logical unit of work, not per record.
What a savepoint does not do
A savepoint is narrower than people often expect.
- It does not protect against unhandled exceptions. Those already roll back the whole transaction.
- It does not snapshot variables. Local variables, static variables, and the
Idfield of inserted records keep their current values after a rollback. The chapter "What a rollback does not revert" covers this. - It does not undo callouts or emails already sent. It only affects database changes.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Setting the savepoint after the DML you want to protect | The rollback cannot undo that DML | Move `setSavepoint()` before the first guarded statement |
| Setting a savepoint and never using it | You spend a DML statement for nothing | Set one only when you have a rollback path |
| Setting a savepoint inside a loop | You can reach 150 DML statements quickly | Set it once outside the loop, or use `allOrNone = false` |
| Storing the savepoint in a static variable and using it in a later request | The savepoint is invalid in a new transaction | Keep it in a local variable within one transaction |
| Catching the exception and rolling back without rethrowing or reporting | Callers believe the work succeeded | Rethrow, return an error result, or log the failure |
Exercise
A method calls Database.setSavepoint() inside a for loop that processes 100 records. Each iteration also runs one insert. Before the loop, the transaction has used 10 DML statements. Does the method stay within the 150 statement limit, and why?
Show answer
No. Each iteration uses one statement for setSavepoint and one for insert, so the loop uses 200 statements. With the 10 already used, the transaction reaches 150 partway through the loop and throws an uncatchable System.LimitException. Set one savepoint before the loop, or use Database.insert(records, false) to handle per-record failures in a single statement.
Exercise
You insert Account A, then set a savepoint, then insert Account B, then catch an exception and roll back to the savepoint. Which accounts exist afterward? What would change if you set the savepoint before inserting Account A?
Show answer
Only Account A exists, because it was inserted before the savepoint and a rollback undoes only work done after the marker. If the savepoint came before Account A, the rollback would undo both accounts.