Skip to content

How to roll back a transaction in PostgreSQL

Undo a change in PostgreSQL with BEGIN and ROLLBACK, keep part of the work with SAVEPOINT, and see what happens to a transaction after an error.

Checked 2026-11-19

A transaction groups statements so they all happen or none do. In PostgreSQL every statement you type outside a transaction is its own transaction and is committed at once, so to be able to undo something you have to open one first.

Undo everything since BEGIN

BEGIN;
UPDATE stock SET quantity = quantity + 5 WHERE store_id = 1 AND product_id = 1;
SELECT quantity FROM stock WHERE store_id = 1 AND product_id = 1;  -- the new value
ROLLBACK;
SELECT quantity FROM stock WHERE store_id = 1 AND product_id = 1;  -- the old value is back

Until COMMIT, nobody else sees your change, and ROLLBACK throws it away. Run it in the sandbox below: the Kestrel shop data is loaded.

Keep part of the work with SAVEPOINT

BEGIN;
UPDATE stock SET quantity = quantity + 10 WHERE store_id = 1 AND product_id = 1;
SAVEPOINT before_order;
INSERT INTO orders (customer_id, store_id, status, total_paise, placed_at)
VALUES (9999, 1, 'pending', 5000, now());  -- fails: there is no customer 9999
ROLLBACK TO SAVEPOINT before_order;
COMMIT;  -- the stock change is kept, the bad order is not

After an error, the transaction is stuck

If any statement inside a transaction fails, PostgreSQL marks the whole transaction as failed. Every statement after that answers:

ERROR:  current transaction is aborted, commands ignored until end of transaction block

Nothing more runs until you end the block. ROLLBACK (or ROLLBACK TO SAVEPOINT) is the way out. COMMIT on a failed transaction also ends it, but it rolls back; nothing is saved.

Things that catch people out

  • TRUNCATE and CREATE TABLE can be rolled back in PostgreSQL (unlike MySQL, where DDL commits on its own).
  • A sequence used by a rolled-back INSERT does not go back: the next id skips a number. Ids are not counts.
  • A GUI client or driver may be in autocommit mode. Check before you rely on ROLLBACK.

Try it in your browser

Practise it on a real machineTransactions & Rollback lab
Open the lab