Sub topic 9
Savepoints and partial rollback
This chapter assumes you can use BEGIN, COMMIT and ROLLBACK, and that you know a failed statement inside a transaction is an error you must handle. The examples use PostgreSQL syntax. The last section notes where other databases differ.
The problem: all or nothing is too coarse
ROLLBACK discards everything since BEGIN. That is the right behavior for atomicity, but sometimes you want to undo only the last step. Typical cases:
- A batch import where one bad row should be skipped, not cancel the other 9,999 rows.
- An optional step, such as applying a promotion code, that may fail while the main work should still go ahead.
- A library or function that wants to try something and recover without knowing whether the caller already opened a transaction.
A savepoint is a named marker inside a transaction. You can later roll back to that marker, which undoes the work done after it while keeping the work done before it. The transaction stays open.
The three commands
| Command | Effect |
|---|---|
| `SAVEPOINT name` | Marks the current point in the transaction. |
| `ROLLBACK TO SAVEPOINT name` | Undoes everything done after the marker. The transaction stays open, and the savepoint stays valid. |
| `RELEASE SAVEPOINT name` | Forgets the marker. The work done after it is kept and becomes part of the enclosing transaction. |
The word SAVEPOINT is optional in the last two commands, so ROLLBACK TO name also works.
Here is the transfer example from the topic plan, using the accounts table from earlier chapters:
BEGIN;
UPDATE accounts SET balance = balance - 10 WHERE id = 1;
SAVEPOINT before_bonus;
UPDATE accounts SET balance = balance + 1000 WHERE id = 2;
ROLLBACK TO SAVEPOINT before_bonus;
COMMIT;
-- Only the first UPDATE is committed.The bonus update never becomes visible to any other session. Savepoints only change what the transaction will commit. They do not change when it commits.
Recovering from an error
In PostgreSQL, any error inside a transaction puts the whole transaction into an aborted state. Later statements fail with current transaction is aborted, commands ignored until end of transaction block until you roll back. A savepoint lets you recover without losing earlier work.
CREATE TABLE items (
sku text PRIMARY KEY,
qty integer NOT NULL CHECK (qty >= 0)
);
BEGIN;
INSERT INTO items (sku, qty) VALUES ('A1', 5);
SAVEPOINT row2;
INSERT INTO items (sku, qty) VALUES ('A1', 7); -- ERROR: duplicate key
ROLLBACK TO SAVEPOINT row2; -- transaction is usable again
INSERT INTO items (sku, qty) VALUES ('B2', 7);
COMMIT;
SELECT sku, qty FROM items ORDER BY sku;
-- A1 | 5
-- B2 | 7The failed insert is discarded, the first insert survives, and the final insert succeeds. Without the savepoint, the only option after the duplicate-key error would have been a full ROLLBACK.
Savepoint lifecycle
A savepoint is not a one-shot marker. You can roll back to it repeatedly, and it disappears only when you release it or roll back to an earlier one.
These rules follow from the diagram:
- After
ROLLBACK TO sp, the savepointspstill exists. You can do more work and roll back to it again. ROLLBACK TO spdestroys every savepoint created aftersp. Savepoints created beforespare untouched.RELEASE spdestroysspand every savepoint created after it. It keeps all the work. It does not undo anything.- If you reuse a savepoint name, the newest one wins. The older one becomes reachable again after the newer one is released.
Here is a nested example:
BEGIN;
INSERT INTO items (sku, qty) VALUES ('C1', 1);
SAVEPOINT a;
INSERT INTO items (sku, qty) VALUES ('C2', 2);
SAVEPOINT b;
INSERT INTO items (sku, qty) VALUES ('C3', 3);
ROLLBACK TO SAVEPOINT a; -- undoes C2 and C3, and destroys b
-- ROLLBACK TO SAVEPOINT b would now fail: savepoint "b" does not exist
COMMIT; -- only C1 is committedSkipping bad rows in a loop
A common pattern is to wrap each unit of work in its own savepoint. In PL/pgSQL, a BEGIN ... EXCEPTION block does this for you. The database sets a savepoint when it enters the block and rolls back to it if the named error is raised.
DO $$
DECLARE
v record;
BEGIN
FOR v IN
SELECT * FROM (VALUES ('A1', 1), ('C3', 3), ('D4', -1)) AS t(sku, qty)
LOOP
BEGIN
INSERT INTO items (sku, qty) VALUES (v.sku, v.qty);
EXCEPTION
WHEN unique_violation OR check_violation THEN
RAISE NOTICE 'skipped %', v.sku;
END;
END LOOP;
END
$$;If items already holds A1 and the other rows are new, A1 is skipped because of the duplicate key. D4 is skipped because of the CHECK constraint. C3 is inserted. The DO block itself runs inside whatever transaction you started, so nothing is committed until you commit.
Savepoints from application code
Most drivers expose savepoints through nested transaction blocks. In psycopg 3, a transaction() block opened inside another one becomes a savepoint:
import psycopg
rows = [("E1", 4), ("E1", 9), ("F2", -3), ("G3", 2)]
with psycopg.connect("dbname=test") as conn:
with conn.transaction(): # BEGIN ... COMMIT
for sku, qty in rows:
try:
with conn.transaction(): # SAVEPOINT ... RELEASE
conn.execute(
"INSERT INTO items (sku, qty) VALUES (%s, %s)",
(sku, qty),
)
except psycopg.errors.IntegrityError as exc:
print(f"skipped {sku}: {exc.diag.message_primary}")When the inner block exits normally, the driver issues RELEASE. When it exits with an exception, the driver issues ROLLBACK TO and re-raises. The try block catches the exception, and the outer transaction carries on. Here E1 (first row) and G3 are committed. The second E1 and F2 are skipped.
What a savepoint does and does not undo
- Data changes: Rows inserted, updated or deleted after the savepoint are undone.
- Locks: In PostgreSQL, locks taken after the savepoint are released on rollback. Locks taken before it stay.
- Sequences: Calls to
nextvalare not undone. A rolled-back insert still consumes an identity or serial value, so gaps in generated IDs are normal. - Session state:
SETchanges are rolled back, but anything outside the database is not. If your code sent an email or called an API after the savepoint, rollback cannot recall it.
Cost
Each active savepoint is a subtransaction with its own transaction ID once it writes data. That has a price:
- PostgreSQL caches up to 64 subtransaction IDs per session. Beyond that, other sessions must look up subtransaction status in a shared structure, which can slow concurrent queries noticeably.
- A PL/pgSQL
EXCEPTIONblock creates a subtransaction every time it runs, so a loop over millions of rows creates millions of them. - Subtransaction IDs count toward transaction ID consumption, which matters for long-running batch jobs.
Use savepoints around units of work that might fail and that you want to skip, not around every statement. If you can avoid the error, do so. For example, INSERT ... ON CONFLICT DO NOTHING skips duplicates without any error and without a savepoint.
Differences between databases
| Database | Create | Roll back to | Release | Behavior after a failed statement |
|---|---|---|---|---|
| PostgreSQL | `SAVEPOINT s` | `ROLLBACK TO s` | `RELEASE s` | Transaction is aborted until you roll back to a savepoint or fully. |
| MySQL (InnoDB) | `SAVEPOINT s` | `ROLLBACK TO s` | `RELEASE SAVEPOINT s` | Only the failed statement is undone by default, so the transaction remains usable. |
| SQL Server | `SAVE TRANSACTION s` | `ROLLBACK TRANSACTION s` | none | Depends on the error and the `XACT_ABORT` setting. |
Because of these differences, code that relies on "the transaction is still usable after an error" works on MySQL but fails on PostgreSQL. Putting a savepoint around the risky statement makes the intent explicit and portable.
Exercise
A transaction runs INSERT X, then SAVEPOINT a, then INSERT Y, then SAVEPOINT b, then INSERT Z, then ROLLBACK TO SAVEPOINT a, then INSERT W, then COMMIT. Which inserts are committed? Can you still run ROLLBACK TO SAVEPOINT b just before the COMMIT?
Show answer
X and W are committed. Y and Z were made after savepoint a, so rolling back to a undoes them. Savepoint b was created after a, so it was destroyed by that rollback, and ROLLBACK TO SAVEPOINT b would fail with an error saying the savepoint does not exist.
Exercise
In PostgreSQL, you run BEGIN, insert a row, and then a second insert fails with a unique violation. You did not create any savepoint. You then run a third, valid insert. What happens, and how would you change the code so the first and third inserts can still be committed?
Show answer
The third insert fails with "current transaction is aborted, commands ignored until end of transaction block", because the error put the transaction in an aborted state. To keep the first and third inserts, run SAVEPOINT s before the second insert and ROLLBACK TO SAVEPOINT s after it fails. The transaction then becomes usable again, and the third insert and the COMMIT succeed.