Chapter Seven · Trust

Transactions and Safety

Anna wants seats G7 and G8 for Friday night, and "together" is not something any single SQL statement can promise. This chapter introduces the transaction: a bracket drawn around several changes so that they succeed or fail as one. Then it names the four famous guarantees behind the bracket, puts two customers in a race for the same seat, and ends with the one protection that still works after everything else has said yes — the backup.

4 topics

Chapter 6 left the Marquee with a database that says no to bad rows — one row at a time. But real work rarely fits in one statement. Booking a pair of seats is two INSERTs; moving money between accounts is two UPDATEs; signing up a new customer might touch three tables. Between any two statements there is a gap, and in that gap live power cuts, crashes, and other people's writes. This chapter is about closing the gap.

The tool is the transaction, and four topics teach it. Topic 30 meets it where it hurts, with Anna's two seats and the three words BEGIN, COMMIT, and ROLLBACK. Topic 31 names the guarantees you just used: the ACID vocabulary that every database conversation assumes. Topic 32 puts two simultaneous customers on a collision course for one seat and shows why neither gets hurt. And Topic 33 is the honest ending: after COMMIT, the only real undo is a backup you made earlier and actually tested.

One transaction — two changes that land together or not at all
BEGIN;the bracket opens
Book seat G7inside, pending
Book seat G8⚡ crash here? all rolls back
COMMIT;both real, or neither

Topics in This Chapter