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
SAVEPOINTsql
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 blocksql
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