Full answer
sql
CREATE TABLE accounts (id INTEGER PRIMARY KEY, owner TEXT, balance INTEGER NOT NULL CHECK (balance >= 0));
INSERT INTO accounts VALUES (1, 'Ana', 100), (2, 'Bilal', 50);Ana has 100. The first statement takes 30 from Bilal; the second tries to take 200 from Ana and breaks the CHECK:
sql
BEGIN;
UPDATE accounts SET balance = balance - 30 WHERE id = 2;
UPDATE accounts SET balance = balance - 200 WHERE id = 1;
-- error on purposetext
Error: CHECK constraint failed: balance >= 0The transaction is still open. Reading inside it shows that the first update survived the error:
sql
SELECT id, balance FROM accounts ORDER BY id;| id | balance |
|---|---|
| 1 | 100 |
| 2 | 20 |
If the application now ran COMMIT, half a transfer would be saved. Rolling back restores both balances:
sql
ROLLBACK;
SELECT id, balance FROM accounts ORDER BY id;| id | balance |
|---|---|
| 1 | 100 |
| 2 | 50 |
In PostgreSQL, any statement after the error fails with "current transaction is aborted, commands ignored until end of transaction block", and COMMIT turns into a rollback (described from the documentation, not run as a multi-step session here). Savepoints let PostgreSQL code recover from an expected error without abandoning the whole transaction.
sql
CREATE TABLE accounts (id INTEGER PRIMARY KEY, owner TEXT, balance INTEGER NOT NULL CHECK (balance >= 0));
INSERT INTO accounts VALUES (1, 'Ana', 100), (2, 'Bilal', 50);
-- error on purpose
BEGIN;
UPDATE accounts SET balance = balance - 30 WHERE id = 2;
UPDATE accounts SET balance = balance - 200 WHERE id = 1;
SELECT id, balance FROM accounts ORDER BY id;
ROLLBACK;
SELECT id, balance FROM accounts ORDER BY id;Checked on SQLite 3.46.1, run twice with identical output.
Key points
- SQLite rolls back only the failing statement
- The SQLite transaction stays open with earlier changes
- PostgreSQL aborts the whole transaction
- Always ROLLBACK in the error handler
Common mistakes
- Committing after a caught error in SQLite
- Assuming one failure undoes the whole transaction on every engine
Follow-ups
- How would a savepoint help here?
- How do database drivers usually handle this?
Tips
- Show the open transaction state