Lesson 23 — Transactions & rollback
Transactions: all or nothing
A transaction groups several changes so they either all happen (COMMIT) or none do (ROLLBACK). Moving money is the classic case: subtract from one account and add to another. If the second step fails, the first must be undone, or money vanishes. In Python, with db: starts a transaction that commits if the block finishes and rolls back if an error is raised.
with db:
db.execute("UPDATE ...")
raise ValueError("oops") # -> everything in the block is undone
Why it matters: banks, shops and booking systems rely on transactions to keep data consistent when things go wrong.
Wrap the two UPDATEs in a with db: block, so the failed transfer is fully rolled back. Expected: balances stay 100 and 50.
Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.
A quick 3-question quiz on this lesson — instant feedback.
Ready for more? Optional paid resources that pick up where this lesson leaves off.
Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.
Project-based Databases & SQL courses if you want a structured paid path after the free lessons. Wait for a sale — prices drop often.
Browse on Udemy →Search Amazon for Databases & SQL books — check the publication year so the examples match current versions.
Search Amazon →