Chapter 4 introduced transactions as all-or-nothing. This chapter is what happens when many transactions run at once — the guarantees MySQL gives you, the ways concurrent access can go wrong, and the dials you turn to trade safety for speed.
ACID — the four guarantees
| Property | Means |
|---|---|
| Atomicity | All statements commit together, or none do |
| Consistency | A transaction moves the DB between valid states |
| Isolation | Concurrent transactions don't corrupt each other |
| Durability | Once committed, it survives a crash |
InnoDB (MySQL's default engine) is fully ACID; the older MyISAM engine is not — another reason to use InnoDB.
Concurrency anomalies
Without isolation, simultaneous transactions can see wrong data:
- Dirty read — reading another transaction's uncommitted (possibly-rolled-back) change.
- Non-repeatable read — a row you re-read has changed mid-transaction.
- Phantom read — a re-run query returns new rows that appeared meanwhile.
Isolation levels
Higher levels prevent more anomalies but reduce concurrency. MySQL's InnoDB default is REPEATABLE READ:
| Level | Prevents |
|---|---|
| READ UNCOMMITTED | nothing (allows dirty reads) |
| READ COMMITTED | dirty reads |
| REPEATABLE READ | dirty + non-repeatable reads (MySQL default) |
| SERIALIZABLE | everything (as if run one at a time) |
SET TRANSACTION ISOLATION LEVEL READ COMMITTED;START TRANSACTION;SELECT balance FROM accounts WHERE id = 1 FOR UPDATE; -- lock the rowUPDATE accounts SET balance = balance - 100 WHERE id = 1;COMMIT;
Locking & deadlocks
Practice
In two client sessions, start transactions and observe a lock: one SELECT … FOR UPDATE blocks the other until commit. Try READ COMMITTED vs REPEATABLE READ and watch whether a re-read sees a committed change. Describe one way to avoid a deadlock in your own code.
Key takeaways
- 01ACID = Atomicity, Consistency, Isolation, Durability; InnoDB provides all four.
- 02Concurrency anomalies: dirty reads, non-repeatable reads, phantom reads.
- 03Isolation levels trade safety for concurrency; MySQL InnoDB defaults to REPEATABLE READ.
- 04SELECT … FOR UPDATE locks rows so another transaction must wait.
- 05Deadlocks are detected and one transaction is rolled back — keep transactions short and lock in a consistent order.
