BeginnerCoder

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.

Want it another way?
Task

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.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.

Keep going with Databases & SQL

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.