✏️ Explanatory Question
Level: Advanced — The cornerstone of reliable databases; asked in virtually every senior interview.
A transaction is a single logical unit of work made up of one or more SQL statements that must execute together as an all-or-nothing operation. If any statement fails, the entire transaction is rolled back, leaving the database unchanged.
The classic example is a bank transfer: debiting one account and crediting another must both succeed, or neither should happen.
| Property | Guarantees | Achieved By |
|---|---|---|
| Atomicity | All or nothing | Undo logs / ROLLBACK |
| Consistency | Valid state to valid state | Constraints, triggers |
| Isolation | No interference | Locking, isolation levels |
| Durability | Permanent changes | Redo logs, disk flush |
-- Start a transaction
START TRANSACTION;
-- Debit account A
UPDATE accounts SET balance = balance - 1000 WHERE acc_id = 1;
-- Credit account B
UPDATE accounts SET balance = balance + 1000 WHERE acc_id = 2;
-- If both succeed, make changes permanent (Durability)
COMMIT;
-- If something went wrong, undo everything (Atomicity)
-- ROLLBACK;
autocommit = 1 mode, where each statement is its own transaction. Use START TRANSACTION (or SET autocommit = 0) to group multiple statements.