Databases
Transactions (all-or-nothing)
There is no extra Big-O cost from the logic itself. The guarantee is about correctness (all-or-nothing), not speed. Real databases pay a small bookkeeping cost so they can roll back if needed.
The idea, in plain English
A transaction is like an ATM transfer between two bank accounts. The money must leave one account and arrive in the other, or neither must happen. You would never accept '$30 vanished from account A but never showed up in B'. A transaction guarantees that cannot happen.
How it works
- 1BEGIN TRANSACTION marks the start. Every change after this point is provisional. It is not yet permanent.
- 2Make your changes, such as subtracting from one account and adding to another. If everything succeeds, COMMIT makes the changes permanent.
- 3If anything goes wrong partway through, such as insufficient funds, ROLLBACK undoes every change made since BEGIN. The database ends up exactly as if nothing had happened.
When you'd use it
Use a transaction any time multiple changes must succeed or fail together. For example: moving money between accounts, or placing an order that both charges a customer and reduces stock.
Common beginner mistakes
- Do not commit changes one at a time instead of wrapping them in one transaction. That is exactly how you get a 'money left but never arrived' bug.
- If you forget to roll back on error, you can leave the data half-changed and inconsistent.
Try it — edit and run
Click the code to edit · press ⌘/Ctrl+↵ to run
Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.
Before: A:100 B:50
SQL: BEGIN TRANSACTION ... COMMIT
Transfer 30 from A to B: success
After transfer 1: A:70 B:80
SQL: BEGIN TRANSACTION ... ROLLBACK
Transfer 200 from B to A: failed (insufficient funds) - rolled back
After transfer 2 attempt: A:70 B:80Not sure this is the right topic? See the learning paths → or where this leads →