Transactions & ACID
Group several statements into one all-or-nothing step with BEGIN and COMMIT, and learn what ACID promises and what a failed transaction does.
All or nothing
A transaction bundles several statements into one all-or-nothing step. You open it with BEGIN, run your statements, then end it with COMMIT to keep every change, or ROLLBACK to throw them all away.
Even without BEGIN, every single statement is its own tiny transaction: it is committed on its own as soon as it succeeds. Only a block between BEGIN and COMMIT groups several statements together.
Money must not appear or vanish
Moving 100 from Alice to Bob takes two updates: take 100 from Alice, add 100 to Bob. If the program crashes between them, one account is changed and the other is not. A transaction makes the two updates succeed together or fail together.
A transfer in a transaction
BEGIN;
UPDATE accounts SET balance = balance + 40 WHERE name = 'Bob';
UPDATE accounts SET balance = balance - 40 WHERE name = 'Alice';
COMMIT;After the first update, this session sees Bob with 90, but every other session still sees 50. After COMMIT, everyone sees both changes at the same moment.
ACID is the short name for four promises. Atomic: all or nothing. Consistent: the rules (constraints) hold before and after. Isolated: other sessions do not see half-finished work. Durable: once COMMIT is reported, the change is saved to disk and survives a crash.
Move money, with and without BEGIN
Step through a transfer of 40, then a transfer of 150. Switch off the transaction and watch what the other sessions see after the failure.
| nametext | balanceinteger |
|---|---|
| Alice | 100 |
| Bob | 50 |
| nametext | balanceinteger |
|---|---|
| Alice | 100 |
| Bob | 50 |
Total money seen by other sessions: 150 (unchanged, as it should be)
Alice has 100 and Bob has 50. The transfer needs two UPDATE statements.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- BEGIN ... COMMIT makes several statements one all-or-nothing step. ROLLBACK cancels them all.
- ACID: atomic (all or nothing), consistent (rules hold), isolated (half-finished work is invisible), durable (committed means saved).
- Without BEGIN, every statement is committed on its own.
- After an error a transaction is aborted. Use ROLLBACK, or SAVEPOINT and ROLLBACK TO to undo just part of it.
Done with this concept?
Mark it complete to track your progress. No login needed.