Part 07 / Topic 3 of 6
Upserts
The upsert is the heart of an idempotent load: insert the row, or update it if the key exists — and with a timestamp guard, let the newest data win even when batches arrive out of order:
# examples/01_idempotent_loads_into_sql_with_an.py
import sqlite3
db = sqlite3.connect(":memory:")
db.execute("""CREATE TABLE shipments (
id TEXT PRIMARY KEY, status TEXT NOT NULL, weight_kg REAL, updated_at TEXT NOT NULL)""")
UPSERT = """INSERT INTO shipments (id, status, weight_kg, updated_at) VALUES (?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET status = excluded.status, weight_kg = excluded.weight_kg,
updated_at = excluded.updated_at
WHERE excluded.updated_at > shipments.updated_at"""
batch1 = [("S-2001", "in_transit", 300.5, "2025-04-02T10:00Z"), ("S-2002", "delivered", 85.0, "2025-04-03T10:00Z")]
batch2 = [("S-2001", "delivered", 300.5, "2025-04-09T10:00Z"), # newer: should win
("S-2002", "in_transit", 85.0, "2025-04-01T10:00Z")] # older, late-arriving: should be ignored
for batch in (batch1, batch1, batch2):
db.executemany(UPSERT, batch)
for row in db.execute("SELECT * FROM shipments ORDER BY id"):
print(row)
The output from the run:
('S-2001', 'delivered', 300.5, '2025-04-09T10:00Z')
('S-2002', 'delivered', 85.0, '2025-04-03T10:00Z')
Walk through what happened: batch1 loaded twice (a re-run) — no duplicates, because the primary key + ON CONFLICT makes the load idempotent. Then batch2 brought a newer status for S-2001 (applied) and an older, late-arriving status for S-2002 (ignored, because excluded.updated_at > shipments.updated_at was false). excluded is SQL's name for "the row that tried to come in". The same statement works in PostgreSQL; MySQL spells it ON DUPLICATE KEY UPDATE.
🧪 Quick quiz
- In the upsert example, a late-arriving older update for S-2002 came in. What happened?
Show the answer
It was ignored because its updated_at was older — the WHERE excluded.updated_at > shipments.updated_at guard kept delivered. (verified against the example output above)
- What makes an INSERT idempotent?
Show the answer
A unique key plus ON CONFLICT handling — an upsert. Without a unique key, every re-run adds duplicates.
Done here? The practice set for Part 7 — 4 exercises with solutions — is on the part page.