Changing data safely

Part of the free LogicWiz Data Engineering course, Module 2: SQL for pipelines. The SQL and Python run in the app, on real Postgres and real Python in the browser.

It is 3:10 on Wednesday morning. Tuesday's nightly load crashed half-way, so you ran it again. Now the reporting table holds 160 orders, the shop took 80, and the alert has your name on it. Nora's goal for you is short: make running a job twice boring.

You'll learn to

  • Load with ON CONFLICT or MERGE so a rerun changes nothing
  • Say which of the two is safe when two sessions race
  • Wrap multi-step changes in a transaction
  • Handle dates and time zones without losing a day

Learn

The rerun doubled everything

Jobs fail. A network blip, a full disk, a source that is down. The fix is almost always "run it again".

That is what happened on Tuesday night. The load used a plain INSERT, and an INSERT appends. The first run put in all 80 orders and then failed at a later step. The rerun put the same 80 in again.

A job is safe to rerun only if it is idempotent: running it twice gives the same result as running it once. Tuesday's load was not.

Append twice, count twice

CREATE TABLE report_orders AS
SELECT order_id, customer_id, status, updated_at
FROM orders;

-- the job fails afterwards, and someone reruns it
INSERT INTO report_orders
SELECT order_id, customer_id, status, updated_at
FROM orders;

SELECT COUNT(*) AS rows_loaded,
       COUNT(DISTINCT order_id) AS orders
FROM report_orders;

160 rows for 80 orders. Nothing failed loudly. The numbers are wrong, and that is all.

Give the load a key and a rule

To make the load idempotent, it needs two things.

The target needs a key: a column that identifies a row. Here it is order_id, the primary key of dw_orders.

And the load must say what to do when that key is already there:

  • ON CONFLICT (order_id) DO UPDATE SET ... updates the row that is there. Inside it, EXCLUDED is the row that tried to go in.
  • ON CONFLICT (order_id) DO NOTHING leaves the old row as it is, however stale.

Insert when the key is new, update when it exists. That is called an upsert.

Remember: a key, plus a rule for "already there". Then a second run finds every key in place, and nothing doubles.

Upsert twice, still 80

INSERT INTO dw_orders (order_id, customer_id, status, updated_at)
SELECT order_id, customer_id, status, updated_at
FROM orders
ON CONFLICT (order_id) DO UPDATE
SET status = EXCLUDED.status,
    updated_at = EXCLUDED.updated_at;

-- exactly the same statement, run again
INSERT INTO dw_orders (order_id, customer_id, status, updated_at)
SELECT order_id, customer_id, status, updated_at
FROM orders
ON CONFLICT (order_id) DO UPDATE
SET status = EXCLUDED.status,
    updated_at = EXCLUDED.updated_at;

SELECT COUNT(*) AS orders,
       COUNT(*) FILTER (WHERE status = 'placed') AS still_placed
FROM dw_orders;

The first run updated the 40 existing orders and inserted 40 new ones. The second run found every key in place and changed nothing you can count: still 80 orders, 8 of them placed.

MERGE: every case in one statement

The real nightly load starts from the landing table of Lesson 2.4. MERGE is the standard SQL statement for that job: sync a target from a source.

You name the match condition once. Then you say what to do in each case:

  • WHEN MATCHED (the key exists): usually UPDATE, often with an extra condition such as "only if the source row is newer". Then an old version that arrives late never overwrites a new one.
  • WHEN NOT MATCHED (a new key): INSERT.
  • Some engines add WHEN NOT MATCHED BY SOURCE (the key vanished from the source): DELETE.

One rule: the source must have one row per key. Feed it the deduplicated latest versions from Lesson 2.4.

Three orders go through the MERGE

Three source rows meet the reporting table: order 1012 is matched and newer so it is updated, order 1009 is matched but not newer so it is left alone, and order 1047 is not matched so it is inserted.

  1. Before. Yesterday's load left orders 1012 and 1009 as placed. Order 1047 is not in the table yet. The source holds the latest version of each order.

  2. Order 1012: matched, and the source is newer. WHEN MATCHED AND s.updated_at > t.updated_at is true, so the row is updated to shipped.

  3. Order 1009: matched, but not newer. The key exists and both timestamps are the same, so no clause applies. The row is left alone.

  4. Order 1047: not matched. The target has no such key, so WHEN NOT MATCHED inserts the row. Run the whole MERGE again and every order is "matched, not newer": nothing changes.

Watch the Target box: each press of Next step sends one source row through the WHEN clauses of the statement below.

MERGE the latest versions into the reporting table

MERGE INTO dw_orders AS t
USING (
  SELECT order_id, customer_id, status, updated_at
  FROM (
    SELECT *,
           ROW_NUMBER() OVER (
             PARTITION BY order_id
             ORDER BY updated_at DESC, loaded_at DESC
           ) AS rn
    FROM stg_orders
  ) ranked
  WHERE rn = 1
) AS s
ON t.order_id = s.order_id
WHEN MATCHED AND s.updated_at > t.updated_at THEN
  UPDATE SET status = s.status, updated_at = s.updated_at
WHEN NOT MATCHED THEN
  INSERT (order_id, customer_id, status, updated_at)
  VALUES (s.order_id, s.customer_id, s.status, s.updated_at);

SELECT status, COUNT(*) AS orders
FROM dw_orders
GROUP BY status
ORDER BY status;

Run it, then add a second copy of the MERGE above the last SELECT and run again: the counts do not move. That is idempotency you can see.

MERGE is a join, and the source must be unique

EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
MERGE INTO dw_orders AS t
USING orders AS s
ON t.order_id = s.order_id
WHEN MATCHED AND s.updated_at > t.updated_at THEN
  UPDATE SET status = s.status, updated_at = s.updated_at
WHEN NOT MATCHED THEN
  INSERT (order_id, customer_id, status, updated_at)
  VALUES (s.order_id, s.customer_id, s.status, s.updated_at);

-- a source with order 1012 twice, like a retried file
MERGE INTO dw_orders AS t
USING (
  SELECT * FROM orders
  UNION ALL
  SELECT * FROM orders WHERE order_id = 1012
) AS s
ON t.order_id = s.order_id
WHEN MATCHED THEN
  UPDATE SET status = s.status;

Postgres plans MERGE as a join of source and target: an outer join when there is a WHEN NOT MATCHED clause, here a Hash Right Join. Each joined row runs the first WHEN clause that is true: Tuples: inserted=40 updated=36 skipped=4. The second statement stops with MERGE command cannot affect row a second time: one target row met two source rows. Deduplicate the source first.

Two writers, one new order

A nightly load has one writer. Dana's app has many, each on its own connection to the database, called a session. Two sessions can try to upsert the same new order in the same instant. Which statement survives that?

ON CONFLICT does. It needs a unique index on the conflict columns, the arbiter, and looks every incoming key up in it.

  • No match: it inserts the row speculatively, then its index entry. If another session inserted the same key in that instant, the speculative row is withdrawn and the check runs again.
  • A match: it locks the existing row, checks the DO UPDATE ... WHERE condition, and writes a new version of the row.

Each row ends as exactly one insert or one update. MERGE makes no such promise.

ON CONFLICT in the plan

-- EXPLAIN ANALYZE really runs the statement
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
INSERT INTO dw_orders (order_id, customer_id, status, updated_at)
SELECT order_id, customer_id, status, updated_at
FROM orders
ON CONFLICT (order_id) DO UPDATE
SET status = EXCLUDED.status,
    updated_at = EXCLUDED.updated_at
WHERE EXCLUDED.updated_at > dw_orders.updated_at;

-- and once more: the rerun
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
INSERT INTO dw_orders (order_id, customer_id, status, updated_at)
SELECT order_id, customer_id, status, updated_at
FROM orders
ON CONFLICT (order_id) DO UPDATE
SET status = EXCLUDED.status,
    updated_at = EXCLUDED.updated_at
WHERE EXCLUDED.updated_at > dw_orders.updated_at;

First run: Conflict Arbiter Indexes: dw_orders_pkey, Tuples Inserted: 40, Conflicting Tuples: 40, and Rows Removed by Conflict Filter: 4 (four orders were not newer). The rerun: 80 conflicts, 80 removed by the filter, nothing written. The WHERE on DO UPDATE is what makes the rerun free.

Two sessions upsert the same new order

Session A inserts order 1101 with ON CONFLICT; session B tries the same key, waits for A, then updates the row A committed. With MERGE instead, B finds no match in its snapshot, inserts, and fails with a duplicate key error.

Read it top to bottom. Above the line, session B waits for A and then updates: no error. Below it, the same race with MERGE ends in a duplicate key error. The Postgres docs say it plainly: ON CONFLICT DO UPDATE guarantees an insert or an update for every row, and MERGE does not. Use ON CONFLICT where several writers upsert the same keys, and MERGE for one writer syncing a table, as in a nightly load.

A job that dies half-way

Some loads take two statements: delete a day, then insert it again. If the job dies in between, the day is empty and the dashboard shows a hole.

A transaction makes several statements one unit. BEGIN opens it. COMMIT keeps everything since BEGIN. ROLLBACK undoes everything since BEGIN. A crash before COMMIT rolls back by itself.

So other people see either the old day or the new day. They never see the gap.

ROLLBACK, and the locks a transaction holds

BEGIN;

DELETE FROM dw_orders
WHERE order_id > 1030;

SELECT COUNT(*) AS during_the_job
FROM dw_orders;

-- the table-level locks this transaction holds
SELECT mode, granted
FROM pg_locks
WHERE relation = 'dw_orders'::regclass
ORDER BY mode;

-- the INSERT that should follow fails: undo everything since BEGIN
ROLLBACK;

SELECT COUNT(*) AS after_rollback
FROM dw_orders;

30 rows inside the transaction, 40 after ROLLBACK. The DELETE holds RowExclusiveLock on the table, the lock every INSERT, UPDATE, DELETE and MERGE takes. The ten deleted rows' own locks are not in pg_locks: row locks live in the rows themselves (their xmax), so Postgres can lock millions of rows without running out of lock memory. Another session updating one of them would wait for COMMIT or ROLLBACK.

Postgres never overwrites a row

How can a reader still see the old day while your transaction is half done? Because Postgres never overwrites a row.

An UPDATE writes a new row version and stamps the old one with the id of the transaction that replaced it. A DELETE only stamps. Each version carries two stamps: xmin, who wrote it, and xmax, who deleted it.

Every reader works from a snapshot: a note of which transactions had committed when it looked. It sees only the versions its snapshot allows. So readers never wait for writers, and nobody sees half a job.

This is MVCC, multi-version concurrency control. Old versions stay behind as dead rows until a clean-up job called VACUUM removes them.

Every version has an address

-- ctid: (page, slot) of the version; xmin: the transaction that wrote it
SELECT ctid, xmin, xmax, order_id, status
FROM dw_orders
WHERE order_id IN (1011, 1012)
ORDER BY order_id;

UPDATE dw_orders
SET status = 'shipped'
WHERE order_id = 1012;

SELECT ctid, xmin, xmax, order_id, status
FROM dw_orders
WHERE order_id IN (1011, 1012)
ORDER BY order_id;

Order 1012 moves from (0,12) to (0,41). That pair is its ctid, its address: page 0, slot 41. The UPDATE wrote a new version in the next free slot and left the old one behind. Postgres calls a row version a tuple, so the old one is a dead tuple. The xmin of 1012 is now one higher: the id of the UPDATE's transaction. Your xmin numbers change from run to run; the ctids do not.

When the snapshot is taken

One setting decides when a transaction takes its snapshot. It is called the isolation level.

  • Read Committed, the default, takes a new snapshot for every statement. So a transaction can read the same row twice and get two answers.
  • Repeatable Read keeps the snapshot of the transaction's first statement. If it then writes a row that another transaction changed, it fails with could not serialize access due to concurrent update, and the application must retry.

Read Committed is fine for most loads. It has one classic accident, the lost update: two jobs read a value, each works out a new one in application code, and the second write silently replaces the first.

Two sessions, two snapshots

Two sessions read and update order 1012 on one heap page: each tuple shows xmin and xmax, session A reads with its own snapshot in Read Committed or Repeatable Read, and the commit log shows which transactions committed.

Step through it in Read Committed. Then switch session A to Repeatable Read and step again. Watch which version A sees after B commits, and what happens when A tries to update the row.

Isolation levels in Postgres, and what each allows

LevelDirty readNon-repeatable readPhantom readSerialization anomaly
Read Uncommittednot in Postgrespossiblepossiblepossible
Read Committed (default)nopossiblepossiblepossible
Repeatable Readnononot in Postgrespossible
Serializablenononono

Read across a row: "possible" is an accident that level lets through. A dirty read sees another transaction's uncommitted change. A non-repeatable read gets two answers for one row. A phantom read repeats a query and finds a different set of rows. A serialization anomaly is a result that no one-at-a-time order of the transactions could give. Serializable also tracks read/write dependencies and fails with could not serialize access due to read/write dependencies among transactions. Read Uncommitted behaves exactly like Read Committed in Postgres.

A lost update in Read Committed

Two jobs read a gift card balance of 50 dollars, each subtracts its own refund in application code and writes the result back; the second write silently replaces the first.

Read it top to bottom: both jobs read 50 before either writes. Nothing failed. B wrote a number worked out from a stale read. Had A not committed yet, B's UPDATE would have waited for A's row lock, then still written 35. Three fixes: an atomic UPDATE ... SET balance = balance - 15; SELECT ... FOR UPDATE, so B's read waits for A; or Repeatable Read, which turns the second write into a serialization error to retry.

Which day is it? Store UTC.

There is one more way to lose rows that loaded safely: put them on the wrong day.

Postgres has two timestamp types. TIMESTAMP is a wall-clock reading with no zone. TIMESTAMPTZ is an exact instant: what you type is converted to UTC and stored as UTC. The zone you typed is not kept. On output it is shown in the session's TimeZone.

SwiftKart stores UTC in plain TIMESTAMP columns, a common convention: store UTC, convert at the edges.

"Which day was this order?" depends on where you stand. 23:30 UTC on 1 June is 08:30 on 2 June in Tokyo. (order_ts AT TIME ZONE 'UTC') AT TIME ZONE 'Asia/Tokyo' first says the stored value is UTC, then reads Tokyo's clock.

The same orders, two calendars, and a short day

SELECT DATE(order_ts) AS utc_date,
       DATE((order_ts AT TIME ZONE 'UTC') AT TIME ZONE 'Asia/Tokyo') AS tokyo_date,
       COUNT(*) AS orders
FROM orders
WHERE order_ts < '2025-06-04'
GROUP BY 1, 2
ORDER BY 1, 2;

-- London moved its clocks forward on 30 March 2025
SET TIME ZONE 'Europe/London';
SELECT TIMESTAMPTZ '2025-03-31 00:00 Europe/London'
       - TIMESTAMPTZ '2025-03-30 00:00 Europe/London' AS day_length,
       TIMESTAMPTZ '2025-03-30 00:00 Europe/London' + INTERVAL '1 day' AS plus_1_day,
       TIMESTAMPTZ '2025-03-30 00:00 Europe/London' + INTERVAL '24 hours' AS plus_24_hours;

Every UTC day splits in two: orders placed after 15:00 UTC already belong to the next day in Tokyo. Then daylight saving: in London, 30 March 2025 lasted 23:00:00. + 1 day keeps the clock time and lands on midnight. + 24 hours adds elapsed time and lands on 01:00. An hourly job that steps by 24 hours drifts by an hour twice a year.

The trap: BETWEEN and timestamps do not mix. order_ts BETWEEN '2025-06-01' AND '2025-06-07' stops at midnight at the start of 7 June, so the whole of 7 June is lost. Use a half-open range: order_ts >= '2025-06-01' AND order_ts < '2025-06-08'. It includes every moment of the 7th, never counts midnight twice when you load day by day, and can use an index.

Numbers to remember

WhatNumber or nameWhat it means
ON CONFLICT with no unique indexthere is no unique or exclusion constraint matching the ON CONFLICT specificationIt needs an arbiter index on the conflict columns
Two incoming rows with the same keyON CONFLICT DO UPDATE command cannot affect row a second timeMERGE stops the same way. Deduplicate the source first
DO UPDATE ... WHERE EXCLUDED.updatedat dworders.updatedatThe same guard as WHEN MATCHED AND ...An older version never replaces a newer one, and a rerun writes nothing
RowExclusiveLockTaken by every INSERT, UPDATE, DELETE and MERGEIt conflicts only with heavier table locks, such as those of CREATE INDEX or ALTER TABLE
COMMITWrites a commit record to the WALThe WAL is the write-ahead log (Lesson 6.7). The transaction is then marked committed
SQLSTATE 40001Both serialization errorsThe application must retry the whole transaction
TIMESTAMP and TIMESTAMPTZ8 bytes each, to the microsecondTIMESTAMPTZ stores UTC and shows it in the session's TimeZone
INTERVAL '1 day' against '24 hours'Clock time against elapsed timeDaylight saving makes local days 23 or 25 hours long. Both follow the session's TimeZone: set it explicitly in jobs
Airflow's data intervalA half-open range in UTCExactly the filter in the warning above (Module 9)
MERGE in other enginesDelta Lake, Snowflake, BigQuery, SQL ServerThe same statement, and how most incremental loads land (Modules 6 and 13)

What changed at SwiftKart

By breakfast the nightly load is a MERGE on order_id, fed with the latest version of each order, and it only updates when the source is newer. You run it twice on purpose. The reporting table says 80 orders both times.

The delete-and-insert step of another job now sits inside one transaction. And the daily filter is a half-open range in UTC.

Running a job twice is boring now. That was the goal.

One mystery is left in this module. The revenue report took 4 seconds in May and takes 40 minutes in June, and nobody touched the SQL. Lesson 2.8 opens the planner to find out why.

In one line

Make loads idempotent with a key plus ON CONFLICT DO UPDATE (safe when sessions race) or MERGE (a join: one writer, a unique source), wrap delete-and-insert in a transaction, and store UTC with half-open date ranges.

Interview corner

How do you make a data load idempotent?

Give the target a business key and load with an upsert: INSERT ... ON CONFLICT DO UPDATE or MERGE, so a rerun updates rows instead of appending them. For whole partitions, delete and reinsert the same date range inside one transaction, or overwrite the partition. Then a failed run can simply be run again, and row counts prove it.

What is the difference between INSERT ... ON CONFLICT and MERGE?

ON CONFLICT is Postgres's upsert: insert, and on a key conflict update or skip. MERGE is the SQL standard: it matches source to target on any condition and can update, insert or delete in one statement, with extra conditions per case. MERGE is what Delta Lake, Snowflake and BigQuery use, so it is the one to know for data engineering. Under concurrency they differ in Postgres: ON CONFLICT probes a unique index and uses a speculative insert, so each row is guaranteed an insert or an update; MERGE is planned as a join on the statement's snapshot, so a key inserted concurrently by another session raises a unique violation, and a source with a key twice fails with cannot affect row a second time.

How do you handle time zones in a pipeline?

Store timestamps as UTC (or as TIMESTAMPTZ), and convert to a local zone only when presenting or when a business day is defined locally. Filter days with half-open ranges, >= start AND < next start, never BETWEEN on timestamps. Every daily report should state which zone its days are in.

What isolation level does Postgres use by default, and when would you change it for a pipeline?

Read Committed: every statement takes a fresh snapshot, so there are no dirty reads but a transaction can see a row change between two reads, and a read-then-write in application code can lose an update. Repeatable Read keeps one snapshot for the whole transaction, which a job that reads several tables and must see one consistent state wants; a write to a row changed since then fails with SQLSTATE 40001 and must be retried. Serializable adds detection of read/write dependency cycles, such as write skew, at the cost of more retries. For upserts from several writers I rely on ON CONFLICT, which guarantees an insert or an update per row even in Read Committed.