skipnothing/SQL

Transactions & ACID

An accounts table holds $300 across two rows. Move $100 from one to the other as a debit then a credit, let the machine die between them, and $100 is simply gone: one row charged, the other never paid.

  • ▸Two writes run back to back leave a half-done gap: a crash there strands one row changed, the other not.
  • ▸Fence those two writes and no crash can leave the half-charged middle behind: the pair lands whole or rewinds whole.
  • ▸A write can finish cleanly and still leave a balance negative: the database enforces only the rules you declared.
BUILDS ON
01

A transfer in two writes

An accounts table holds two rows: account 1 with a balance of 200, account 2 with 100. Moving $100 from account 1 to account 2 takes two writes: UPDATE accounts SET balance = balance - 100 WHERE id = 1, then UPDATE accounts SET balance = balance + 100 WHERE id = 2. Run both and the balances read 100 and 200. The total across the table, 300, never moved.

Now let the process die between the two writes. The first one already ran: account 1 is down to 100. The second never fires: account 2 is still at 100. The table now totals 200. A hundred dollars has left one account and arrived nowhere. Re-running blindly could charge account 1 a second time.

Nothing here is broken syntax. Each write did exactly what it said. The damage is in the gap between them, a moment where the data is half-changed and, to anyone reading, simply wrong.

A TRANSFER TORN IN HALF

Keep going, sign up to unlock the rest

4 more parts in this topic, plus 30+ more topics in SQL.

Sign up, it's freeSee the full SQL
Writes, Constraints & Transactions0/4#25 Constraints
#27 Isolation Levels & Locks