Transactions & savepoints
◈ 2 cardsAll-or-nothing changes, and partial rollback.
All or nothing
A transaction groups statements so they all commit together or not at all — the heart of data integrity (the classic example: a bank transfer must debit and credit, never just one):
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT; -- or ROLLBACK to undo everything
Inside a transaction, a savepoint is a checkpoint you can roll back to without abandoning the whole transaction:
SAVEPOINT sp1;
...risky change...
ROLLBACK TO SAVEPOINT sp1; -- undo just that part
(The exercises below run inside a managed transaction, so you'll use savepoints to see rollback in action safely.)