1 Understanding Transactions
TopA transaction is a group of SQL operations that must succeed or fail as a unit. If any step fails, everything rolls back as if nothing happened. The classic example: a bank transfer.
The Bank Transfer Problem
Transferring $500 from Account A to Account B requires two operations:
- Subtract $500 from Account A
- Add $500 to Account B
If step 1 succeeds but step 2 fails (server crash, network error), $500 vanishes. Transactions prevent this.
-- Without a transaction (DANGEROUS)
UPDATE accounts SET balance = balance - 500 WHERE id = 1;
-- 💥 Server crashes here!
UPDATE accounts SET balance = balance + 500 WHERE id = 2;
-- $500 is gone forever-- With a transaction (SAFE)
START TRANSACTION;
UPDATE accounts SET balance = balance - 500 WHERE id = 1;
UPDATE accounts SET balance = balance + 500 WHERE id = 2;
COMMIT; -- Both succeed → make it permanent
-- If anything fails → ROLLBACK undoes everythingTransaction Commands
| Command | What It Does |
|---|---|
START TRANSACTION | Begins a new transaction |
COMMIT | Saves all changes permanently |
ROLLBACK | Undoes all changes since START TRANSACTION |
SAVEPOINT name | Creates a checkpoint you can roll back to |
ROLLBACK TO name | Rolls back to a savepoint (not the entire transaction) |
Using SAVEPOINT for Partial Rollbacks
START TRANSACTION;
INSERT INTO orders (customer_id, product, amount)
VALUES (1, 'SQL Course', 49.99);
SAVEPOINT before_bonus;
UPDATE customers SET loyalty_points = loyalty_points + 50
WHERE id = 1;
-- Oops, bonus logic was wrong. Undo just the bonus, keep the order.
ROLLBACK TO before_bonus;
COMMIT; -- The order is saved; the bonus is notMySQL auto-commit: By default, MySQL runs in auto-commit mode — every single statement is its own transaction that auto-commits. When you explicitly use START TRANSACTION, auto-commit is disabled until you COMMIT or ROLLBACK.
Key Takeaways
- A transaction groups multiple operations into an all-or-nothing unit
-
START TRANSACTION→ do work →COMMIT(save) orROLLBACK(undo) - Use
SAVEPOINTfor partial rollbacks within a transaction - Without transactions, failures can leave your data in an inconsistent state