← Back to SQL, page 12

sql-0225 · Hard senior

Inside a transaction, the second of two UPDATEs fails a CHECK constraint. Is the first UPDATE undone automatically?

Not in SQLite: only the failing statement is rolled back, and the transaction stays open with the first UPDATE still applied until the application issues ROLLBACK or COMMIT. PostgreSQL marks the whole transaction as aborted, rejects further statements, and can only roll back. In both cases the application must catch the error and roll back explicitly.

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 purpose
text
Error: CHECK constraint failed: balance >= 0

The transaction is still open. Reading inside it shows that the first update survived the error:

sql
SELECT id, balance FROM accounts ORDER BY id;
idbalance
1100
220

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;
idbalance
1100
250

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