Lesson 24 / 28

Transactions

Group statements so they succeed or fail together.

ACID, briefly

ACID — Atomicity, Consistency, Isolation, Durability — describes the guarantees a transaction gives you.

BEGIN, COMMIT, ROLLBACK

Wrap related statements between START TRANSACTION and COMMIT; ROLLBACK undoes everything since the start if something goes wrong.

START TRANSACTION;
UPDATE accounts SET balance = balance - 500 WHERE id = 1;
UPDATE accounts SET balance = balance + 500 WHERE id = 2;
COMMIT;

Why it matters

Without a transaction, a crash between the two UPDATEs above would leave money deducted from one account but never added to the other.