Sub topic 9
Savepoints and Partial Rollback
This chapter assumes you know basic SQL statements, primary keys, constraints, and how concurrent database sessions work. It also assumes the database supports transactions and savepoints, as PostgreSQL does.
Why savepoints exist
A transaction groups several operations into one unit. COMMIT makes all its changes permanent. ROLLBACK removes all changes made by the transaction.
Sometimes a transaction contains independent stages. You may want to keep the successful stages while undoing only one failed stage. A savepoint is a named position inside a transaction. ROLLBACK TO SAVEPOINT returns the transaction to that position.
The changes made before the savepoint remain. Changes made after it are undone.
CREATE TABLE accounts (
id integer PRIMARY KEY,
balance numeric(12,2) NOT NULL CHECK (balance >= 0)
);
INSERT INTO accounts (id, balance)
VALUES (1, 100.00), (2, 50.00);
BEGIN;
UPDATE accounts
SET balance = balance - 10
WHERE id = 1;
SAVEPOINT before_bonus;
-- This violates the balance >= 0 constraint.
UPDATE accounts
SET balance = balance - 500
WHERE id = 1;
-- Undo only the failed stage.
ROLLBACK TO SAVEPOINT before_bonus;
COMMIT;
SELECT * FROM accounts ORDER BY id;
-- Account 1 has 90.00. The first update was kept.In PostgreSQL, the failed update puts the transaction into an error state. The savepoint makes recovery possible. Without it, the application would need to roll back the entire transaction.
Savepoint commands
| Command | Effect |
|---|---|
| `SAVEPOINT name` | Marks the current position in the transaction |
| `ROLLBACK TO SAVEPOINT name` | Undoes changes after that position |
| `RELEASE SAVEPOINT name` | Removes the savepoint while keeping its changes |
| `ROLLBACK` | Undoes the entire transaction |
A savepoint does not commit anything. Until the outer transaction commits, other sessions generally cannot treat the retained changes as permanent.
After rolling back to a savepoint, that savepoint remains available. You can continue working and roll back to it again. Later savepoints are removed. An application can also create several savepoints, similar to nested checkpoints.
BEGIN;
UPDATE accounts
SET balance = balance - 10
WHERE id = 1;
SAVEPOINT before_second_step;
UPDATE accounts
SET balance = balance + 10
WHERE id = 2;
RELEASE SAVEPOINT before_second_step;
COMMIT;RELEASE SAVEPOINT does not undo the work after the savepoint. It only says that you no longer need that recovery point.
How partial rollback works
Keep the transaction short. A savepoint can undo database changes, but application code must also discard or correct any in-memory assumptions based on the undone work.
Exercise
After ROLLBACK TO SAVEPOINT s, can the transaction still commit changes made before s?
Show answer
Yes. Changes before s remain, and the transaction can commit them unless another error occurs.