What CRUD Leaves Out: A First Look at Transactions
Beginner tutorials teach CRUD: create, read, update and delete. They often skip an idea that makes those operations safe when several belong together: the transaction. This post introduces it with the classic example.
The classic example
Moving money between two accounts takes two updates:
UPDATE accounts SET balance = balance - 50 WHERE id = 1;
UPDATE accounts SET balance = balance + 50 WHERE id = 2;
What if the program crashes between the two lines? Account 1 has lost 50, and account 2 never received it. The money vanished.
The idea
A transaction groups statements so that they all happen, or none of them do:
BEGIN;
UPDATE accounts SET balance = balance - 50 WHERE id = 1;
UPDATE accounts SET balance = balance + 50 WHERE id = 2;
COMMIT;
COMMIT makes the changes permanent. If anything goes wrong before it, the database undoes the partial work. You can also undo on purpose:
ROLLBACK;
The four promises, in plain words
Database books describe transactions with the letters ACID:
| Letter | Word | Plain meaning |
|---|---|---|
| A | Atomic | All or nothing |
| C | Consistent | Rules such as NOT NULL and foreign keys still hold afterwards |
| I | Isolated | Other users do not see your half-finished changes |
| D | Durable | Once committed, the change survives a crash |
You do not need to memorise these. "All or nothing, and nobody sees the half-done version" covers most of it.
Transactions from Python
Python's sqlite3 module starts a transaction for you before changes. You finish it with commit(), or undo with rollback(). Using the connection in a with block commits on success and rolls back on an error:
import sqlite3
conn = sqlite3.connect("bank.db")
with conn:
conn.execute("UPDATE accounts SET balance = balance - 50 WHERE id = ?", (1,))
conn.execute("UPDATE accounts SET balance = balance + 50 WHERE id = ?", (2,))
A very common beginner bug is forgetting to commit, then wondering why changes are missing the next time the program runs.
A learning trick
Transactions double as an undo button while practising. Try a risky statement inside one, look at the result, and roll back:
BEGIN;
DELETE FROM pets;
SELECT COUNT(*) FROM pets; -- 0, oh no
ROLLBACK;
SELECT COUNT(*) FROM pets; -- all back
When to use transactions
- whenever two or more changes must succeed together
- when you read something and then change it based on what you read
- while experimenting, as a safety net
Keep them short
While a transaction is open, the database may hold locks that make other users wait. Do the database work, commit, and only then do slow things like sending emails. Our long read on create, read, update and delete puts transactions in the wider CRUD picture.
A free learning page for beginners. Practise on a test database, never on real customer data, and check the official documentation for your database version.