Lesson 29 of 30
97%
Transactions
A transaction is a bundle of SQL that should all succeed or all fail.
Think of transferring stars from Ada to Sam. Both updates must happen.
The three words
1
START TRANSACTION begins the bundle
2
COMMIT saves every change
3
ROLLBACK undoes every change in the bundle
A tiny transfer
sql
Result
Query OK, 1 row affected (Ada 12 → 7 stars)
Query OK, 1 row affected (Sam 3 → 8 stars)
Commit complete
| name | stars |
|---|---|
| Ada | 7 |
| Sam | 8 |
2 rows
If something looks wrong
sql
Result
Query OK, 1 row affected
Rollback complete. Both wallets restored.
| name | stars |
|---|---|
| Ada | 12 |
| Sam | 3 |
2 rows
Engine note
InnoDB tables support transactions. MyISAM tables do not.
New MySQL tables are InnoDB by default. Keep it that way.
Tip: One COMMIT per real-world action. Do not leave a transaction open while you go to lunch.
Test yourself
Three quick questions made just for this lesson. Earn 10 XP per correct answer.