Sub topic 7
Partial Rollback with Savepoints
This chapter assumes you know basic INSERT, UPDATE, and DELETE statements and understand that COMMIT ends a transaction. A savepoint is a named marker inside an open transaction. It lets you undo work performed after that marker without discarding the entire transaction.
Why use a savepoint?
A full ROLLBACK undoes every uncommitted change in the current transaction. ROLLBACK TO SAVEPOINT undoes only the changes made after a selected savepoint.
The transaction remains open after a partial rollback. You can continue changing data, then use COMMIT to make the remaining work permanent or ROLLBACK to discard everything that is still uncommitted.
INSERT INTO accounts (id, owner, balance)
VALUES (3, 'Carol', 500);
SAVEPOINT after_carol;
UPDATE accounts
SET balance = balance - 50
WHERE id = 3;
SAVEPOINT after_debit;
DELETE FROM accounts
WHERE id = 1;
ROLLBACK TO SAVEPOINT after_debit;
COMMIT;After ROLLBACK TO SAVEPOINT after_debit, the DELETE is undone. Carol's balance remains 450 because that update happened before after_debit. The final COMMIT saves both Carol's row and her updated balance.
A savepoint does not save data permanently. It only records a position to which the current transaction can return.
Savepoint behavior
| Operation | Effect on changes | Transaction status |
|---|---|---|
| `SAVEPOINT name` | Records the current position | Remains open |
| `ROLLBACK TO SAVEPOINT name` | Undoes work after the marker | Remains open |
| `COMMIT` | Saves all remaining changes | Ends |
| `ROLLBACK` | Undoes all remaining changes | Ends |
Savepoints are ordered. When you roll back to one, savepoints created after it are erased. Earlier savepoints remain available.
SAVEPOINT first_point;
UPDATE accounts SET balance = balance + 10 WHERE id = 2;
SAVEPOINT second_point;
UPDATE accounts SET balance = balance + 20 WHERE id = 2;
ROLLBACK TO SAVEPOINT first_point;
-- second_point no longer exists
COMMIT;The balance increase of 10 is retained, while the increase of 20 is undone. Attempting to roll back to second_point afterward raises an error because that savepoint was removed.
If you create another savepoint with the same name, Oracle moves that name to the new position. Use clear names that describe the stage of work.
A transaction timeline
Common mistakes
- Expecting
ROLLBACK TO SAVEPOINTto end the transaction. - Trying to use a savepoint after a
COMMITor fullROLLBACK. Both operations remove the transaction's savepoints. - Assuming a savepoint protects against DDL. Oracle DDL can implicitly commit the transaction, so savepoints may disappear.
- Placing a savepoint too late. Work performed before the marker cannot be undone by rolling back to it.
Exercise
You insert a row, create savepoint S1, update the row, create savepoint S2, and delete another row. Which operation undoes only the delete and leaves the update in place?
Show answer
ROLLBACK TO SAVEPOINT S2;