All or nothing: transactions
Database management, lesson five — and the last one before we leave the warehouse for the data lake. Today’s idea: a transaction wraps several SQL statements into one unit that either all succeeds or all fails. Half-written data is the enemy; transactions are how a database refuses to leave it behind.
The code
BEGIN;
DELETE FROM storm_readings
WHERE reading_time < CURRENT_DATE;
INSERT INTO pipeline_log (job_name, status, ran_at)
VALUES ('nightly-purge', 'complete', NOW());
COMMIT;
-- If the INSERT failed: run ROLLBACK; instead
The rule of thumb: whenever a step does two or more writes that only make sense together, wrap them. Without the transaction, a crash between the DELETE and the INSERT leaves deleted readings with no audit trail — the exact half-done state that quietly poisons a warehouse. With it, failure means the table looks exactly as it did before.
In practice
Behind BEGIN/COMMIT/ROLLBACK sits the ACID promise: Atomicity (all or nothing — one unit), Consistency (constraints and rules hold before and after), Isolation (other queries never see your half-finished writes), Durability (once COMMIT succeeds, it survives a crash). A data engineer’s writes are multi-step — bulk loads, backfills, merging an audit row alongside the data — and transactions are what make those steps safe as a group.
This connects straight to your world: the ACID guarantee is exactly what Delta Lake brings to the data lake — atomic merges and overwrites, so a failed pipeline run never leaves a half-updated table sitting in S3.
Python bridge: think of a transaction as try/except with a rollback on the exception — or a with open(...) block that only flushes at the very end. Nothing is real until the block completes.
Further reading
Understanding SQL Transactions: A Comprehensive Guide — DataCamp (a thorough beginner-friendly walkthrough of BEGIN, COMMIT, and ROLLBACK with worked examples)
Try it
Practice question: your pipeline archives a retired station: (1) delete its row from weather_stations (station_id = 7), and (2) insert a row into stations_audit recording the archive. Write the full transaction (BEGIN … COMMIT), and say which single command you’d run if the INSERT failed after the DELETE.
Show answer
BEGIN; DELETE FROM weather_stations WHERE station_id = 7; INSERT INTO stations_audit (station_id, action, logged_at) VALUES (7, 'archived', NOW()); COMMIT; -- If the INSERT failed: ROLLBACK;
Result: run ROLLBACK; and the DELETE is undone too — the station row is back exactly as it was. Either the station is archived and the audit row exists, or nothing changed at all. Never a deleted station with no record.