Transactions and ACID
All or nothing.
When a customer orders a mug, two things must happen. Stock goes down by one, and an order is created. If only one of them happens, the data is wrong. A transaction makes them happen together, or not at all.

- Stock down, order created
- Both or neither
- A transaction
ACID
Good transactions have four properties, called ACID. Atomic means all or nothing. Consistent means the rules always hold, like stock never going below zero. Isolated means transactions running at the same time don't see each other's half finished work. And durable means once it's saved, it survives a crash.
| Letter | Meaning |
|---|---|
| Atomic | all or nothing |
| Consistent | rules always hold |
| Isolated | no half-finished views |
| Durable | survives a crash |
A transaction rolls back
Python comes with SQ Lite, a small relational database. We start with one mug in stock. The transaction lowers the stock, then tries to create an order, but the order fails. Run it. Because both steps were in one transaction, the stock change is undone too. Stock is still one.
import sqlite3
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE stock (item TEXT, qty INT)")
db.execute("CREATE TABLE orders (item TEXT NOT NULL)")
db.execute("INSERT INTO stock VALUES ('mug', 1)")
db.commit()
try:
with db: # one transaction
db.execute("UPDATE stock SET qty = qty - 1 WHERE item = 'mug'")
db.execute("INSERT INTO orders VALUES (NULL)") # fails
except sqlite3.IntegrityError as e:
print("failed:", e)
print("stock:", db.execute("SELECT qty FROM stock").fetchone()[0])failed: NOT NULL constraint failed: orders.item stock: 1
Summary
Transactions make several changes happen together or not at all, with the ACID guarantees. Next, keeping copies of your data on other machines. Replication.
Key takeaways- Atomic
- Consistent, Isolated
- Durable