Transactions & ACID
INSERT, UPDATE, or DELETE, and the database applies it immediately. But real-world operations are often made of several statements that only make sense together. A transaction groups multiple statements into a single, all-or-nothing unit of work: either every statement in the group succeeds and is saved, or none of them are.The classic example: transferring money
Imagine moving $100 from Account A to Account B. That operation is really two separate statements:
Subtract $100 from Account A (a debit).
Add $100 to Account B (a credit).
Two statements that must act as one
UPDATE accounts SET balance = balance - 100 WHERE id = 1; -- debit A UPDATE accounts SET balance = balance + 100 WHERE id = 2; -- credit B
Wrapping both statements in a transaction is what gives you the guarantee that either both updates land, or neither does.
The ACID properties
Property | Meaning |
|---|---|
Atomicity | All statements in the transaction succeed, or none of them are applied — there is no partial result. |
Consistency | A transaction takes the database from one valid state to another, never leaving it in a state that violates constraints or business rules. |
Isolation | Concurrent transactions don't interfere with each other, even when running at the same time against the same data. |
Durability | Once a transaction is committed, the change survives — even a power loss or crash immediately afterward cannot undo it. |
Starting a transaction
BEGIN (or the standard START TRANSACTION, depending on the database). Every statement you run after that point belongs to the same unit of work, until you explicitly end it.Beginning a transaction
BEGIN; UPDATE accounts SET balance = balance - 100 WHERE id = 1; UPDATE accounts SET balance = balance + 100 WHERE id = 2; -- nothing is permanent yet...
COMMIT and ROLLBACK do, and they are the subject of the next page.