AI Hints
Home›PostgreSQL Tutorial›Transactions and MVCC
PostgreSQL · Lesson 65 of 120

Savepoints

Undo just part.

⏱ 2 min read▶ Video at 58:23🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

Sometimes you want to undo just one step, not the whole transaction. A savepoint is a bookmark inside a transaction you can roll back to.

  • A bookmark
  • Undo one step
  • Keep the rest

Roll back to a savepoint

We add a review, then set a savepoint. The next insert fails. Rollback to savepoint undoes only that, and the first review is kept when we commit. Run it. One new review saved.

query.sqlsql
BEGIN;
INSERT INTO reviews (book_id, customer_id, stars, body, created_at)
VALUES (1, 7, 5, 'Loved it.', now());
SAVEPOINT before_second;
INSERT INTO reviews (book_id, customer_id, stars, body, created_at)
VALUES (1, 8, 9, 'Ten out of five!', now());   -- stars must be 1 to 5
ROLLBACK TO SAVEPOINT before_second;
COMMIT;
SELECT count(*) FROM reviews WHERE book_id = 1 AND customer_id IN (7, 8);
Output
BEGIN
INSERT 0 1
SAVEPOINT
ERROR:  new row for relation "reviews" violates check constraint "reviews_stars_check"
DETAIL:  Failing row contains (242, 1, 8, 9, Ten out of five!, 2026-11-14
18:06:42.589507+00).
ROLLBACK
COMMIT
 count
-------
     1
(1 row)

Where savepoints help

Imports where some rows may fail. Trying an insert, and falling back to an update. Libraries that need nested transactions. Most drivers create savepoints for you when you nest transactions.

keyvalue
Importsskip bad rows
Try / fallbackundo one step
Nesteddrivers use them
Costsmall, but not free

Summary

Savepoints let you undo part of a transaction, and keep the rest. Next, how Postgres lets many people read and write at once.

Key takeaways
  • SAVEPOINT
  • ROLLBACK TO
  • Partial undo
Next up: MVCC — many versions of a row