A bank transfer subtracts money from A and adds it to B. Why run both in one transaction?
Options
- To make both of the updates run faster on the database server
- Both changes happen together or neither does, so no money is lost (Correct option)
- Transactions encrypt the data during the transfer of money
- To lock the whole bank database while the update is running
Answer
So both changes happen together or neither happens; a crash in the middle cannot lose money
Why
A transaction groups several statements into one all-or-nothing unit (atomicity).
If the system crashes after subtracting from A but before adding to B, the database rolls back the whole transaction, so A keeps the money.
You start it with BEGIN, finish with COMMIT, or undo with ROLLBACK.
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 'A';
UPDATE accounts SET balance = balance + 100 WHERE id = 'B';
COMMIT;Remember
Transaction = all or nothing.