Quiz
Warm-up from lesson 7-2: what makes `UPDATE accounts SET balance = 0;` so dangerous?
All or nothing
Move $30 from Ana to Ben and you must run TWO updates: subtract from Ana, add to Ben. Now imagine the server dies between them. Ana lost $30, Ben got nothing, and $30 vanished. Partial completion is worse than failure.
A transaction makes a group of statements all-or-nothing:
BEGIN; UPDATE accounts SET balance = balance - 30 WHERE name = 'Ana'; UPDATE accounts SET balance = balance + 30 WHERE name = 'Ben'; COMMIT;
BEGINstarts the transaction. Changes after it are provisional.COMMITmakes them all permanent, together.ROLLBACKinstead throws them ALL away, as if nothing happened.
If the crash happens before COMMIT, the database recovers to the state before BEGIN. Money never half-moves.
Code exercise · sql
Run it. The transfer runs inside a transaction that ends in ROLLBACK, so the final SELECT shows both balances untouched. Change ROLLBACK to COMMIT and rerun to see 70 and 80 instead.
ACID, translated
Databases promise transactions behave well under the acronym ACID:
- Atomic: all of the transaction happens, or none of it. The transfer never half-completes.
- Consistent: the rules always hold. Constraints (lesson 7-3) are never violated, even mid-crash.
- Isolated: concurrent transactions do not see each other's half-done work. Two people buying the last ticket cannot both get it.
- Durable: once COMMIT returns, the data survives a power cut. The database wrote it to disk in a recoverable way before saying yes.
This is the answer to lesson 1-2's promise: this is why thousands of simultaneous users can hammer one database and the data stays sane, and it is what a shared spreadsheet can never give you.
Code exercise · sql
Your turn. Complete the transfer of 30 from Ana to Ben and make it permanent, so the final balances are 70 and 80. You need both UPDATE statements between BEGIN and COMMIT.
Quiz
Halfway through a BEGIN ... COMMIT block, your app discovers the transfer is invalid (the account would go negative). What should it send to the database?