← Back to PostgreSQL, page 1

postgresql-0011 · Easy fresher

Use transactions and savepoints to undo part of a unit of work.

BEGIN starts a transaction, COMMIT makes its changes permanent and ROLLBACK discards them. A SAVEPOINT marks a point inside the transaction; ROLLBACK TO SAVEPOINT undoes work after it while keeping earlier work. After an error in PostgreSQL, the transaction is aborted until you roll back, either entirely or to a savepoint.

Full answer

Setup for the example:

sql
CREATE TABLE stock (item text PRIMARY KEY, qty int CHECK (qty >= 0));
INSERT INTO stock VALUES ('pen', 10), ('ink', 2);
sql
BEGIN; UPDATE stock SET qty = qty - 3 WHERE item = 'pen'; SAVEPOINT before_ink;

Result on PostgreSQL 17:

text
SAVEPOINT
sql
UPDATE stock SET qty = qty - 5 WHERE item = 'ink';

Result:

text
ERROR:  new row for relation "stock" violates check constraint "stock_qty_check"
sql
SELECT * FROM stock;

Output:

text
ERROR:  current transaction is aborted, commands ignored until end of transaction block
sql
ROLLBACK TO SAVEPOINT before_ink; COMMIT; SELECT item, qty FROM stock ORDER BY item;

PostgreSQL returns:

text
 item | qty
------+-----
 ink  | 2
 pen  | 7
(2 rows)

The pen update succeeds and a savepoint is set. Taking five ink from a stock of two violates the CHECK constraint. Any further statement then fails with 'current transaction is aborted, commands ignored until end of transaction block', which surprises developers coming from databases that continue after errors. Rolling back to the savepoint clears the error while keeping the pen change, and COMMIT saves it, so pens drop to 7 and ink stays at 2. Drivers and ORMs often use savepoints for nested transaction blocks.

sql
CREATE TABLE stock (item text PRIMARY KEY, qty int CHECK (qty >= 0));
INSERT INTO stock VALUES ('pen', 10), ('ink', 2);

BEGIN; UPDATE stock SET qty = qty - 3 WHERE item = 'pen'; SAVEPOINT before_ink;

UPDATE stock SET qty = qty - 5 WHERE item = 'ink';

SELECT * FROM stock;

ROLLBACK TO SAVEPOINT before_ink; COMMIT; SELECT item, qty FROM stock ORDER BY item;

Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.

Key points

  • BEGIN, COMMIT and ROLLBACK
  • Savepoints allow partial rollback
  • Errors abort the transaction
  • ROLLBACK TO SAVEPOINT recovers
  • ORMs use savepoints for nesting

Common mistakes

  • Continuing to send statements after an error
  • Holding transactions open for long periods

Follow-ups

  • What does psql's ON_ERROR_ROLLBACK do?
  • How do savepoints affect performance?

Tips

  • Show the aborted-transaction error