Transactions
โ Report an issue with this lessonBEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;
A transaction groups multiple statements so they all succeed or all
fail together โ if the second UPDATE fails, ROLLBACK
undoes the first one too, so money is never deducted from one account
without appearing in the other.
This all-or-nothing guarantee is usually summarized by the acronym
ACID: Atomicity (the whole transaction happens or
none of it does), Consistency (constraints like
CHECK and foreign keys still hold once it's done),
Isolation (one transaction doesn't see another transaction's
half-finished changes), and Durability (once committed, the
change survives even a crash immediately after). Without transactions, a
crash or error between the two UPDATE statements would leave
$100 deducted from one account and never credited to the other -- money
gone.
You can undo a transaction explicitly with ROLLBACK instead
of COMMIT, which is exactly what error-handling code should
do when a step partway through fails:
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
-- application code checks the new balance isn't negative
-- if it is:
ROLLBACK; -- undoes the UPDATE above entirely, as if it never ran
-- otherwise:
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;
A common mistake is running several related statements without wrapping
them in an explicit transaction at all -- by default, SQLite commits each
statement independently, so a failure between two related
UPDATEs leaves the database in a half-changed state with no
way to automatically undo the first one. Any time two or more writes need
to succeed or fail as a single unit -- transferring money, creating an
order and decrementing inventory, anything where "half done" is worse than
"not done" -- that's a signal you need an explicit transaction.
Try it yourself
Run your code and get it working before marking this lesson complete.
9 more lessons โ including Capstone project: a reporting query set โ plus a certificate are waiting.
Unlock the full course โ $149.99