Transactions
A transaction is a set of database operations that you want to succeed all together or not at all — there is no "halfway" state. @@F{1}@@ If you create, update, or delete several records as part of one transaction, the database treats them as a single, indivisible batch.
Imagine moving money between two accounts: money leaves account A, and money arrives in account B. If something breaks between those two steps, you'd be left with the money gone from A but never reaching B. A transaction guarantees that both happen, or neither does — the transfer is never left half-done.
Why transactions matter
- Data stays consistent. Partial or conflicting updates are prevented, so the data never ends up in a strange in-between state.
- Failures are clean. If an outage or an error happens mid-way, the transaction can roll back to its previous state instead of leaving broken or incomplete records.
- Mistakes are recoverable. You can undo a whole batch of changes with one rollback, rather than manually reversing each step.
This is exactly the Atomicity promised by the ACID Properties model — the idea that a group of operations is treated as one unbreakable unit.
How a transaction lives (its states)
Every transaction passes through a lifecycle of states @@F{2}@@:
- Active — the transaction is running; the operations are still being executed.
- Partially committed — the changes have been made, but aren't permanently saved yet. They sit in a temporary buffer until the transaction is sure everything worked.
- Committed — the changes are written permanently to the database and can no longer be rolled back. The work is done.
- Failed — something went wrong (an error, an abort, a system failure). All the changes made so far are discarded, keeping the database consistent.
- Terminated — the final stage. The transaction is over, whether it ended by committing or by failing.
The key idea: anything that happens before a commit is effectively "tentative." Only a commit makes the change real.
When to use transactions
Use a transaction whenever multiple writes must stay in sync:
| Scenario | Why it needs a transaction |
|---|---|
| Moving money between accounts | Both sides of the transfer must happen together |
| Placing an order | Order row + payment + stock deduction are one unit |
| Updating a profile | Old and new values must not be left half-written |
For a single, simple write you generally don't need an explicit transaction — the database handles each statement on its own. Transactions matter when you're grouping several steps that must succeed as one.