SQL Dojo
Pattern

Incremental loads you can rerun

Load only the new rows: a high-water mark with a lookback for late data, a key so that a rerun changes nothing, and a test against a full rebuild.

When a table is too big to rebuild on every run, load only what is new: the rows past the latest one the target already holds, its high-water mark. Jobs get retried, so the load must also be idempotent: a second run changes nothing.

INSERT INTO fct_events
SELECT r.*
FROM raw_events r
WHERE r.occurred_at >= (SELECT MAX(occurred_at) FROM fct_events) - INTERVAL '3 days'
  AND NOT EXISTS (SELECT 1 FROM fct_events f WHERE f.event_id = r.event_id);

Three days of lookback catch the events that arrive late; the key check makes rereading them harmless. To pick up corrected rows as well, delete the window and insert it again, or MERGE on event_id.

The trap. A mark on the event time with no lookback never loads an event that lands behind it, and an INSERT with no key check doubles the window on every retry. Neither raises an error: now and then, rebuild in full and compare key by key with a FULL JOIN, and widen the window when they drift. Only a full refresh removes rows deleted at the source.

In dbt. materialized='incremental' with unique_key='event_id'; the filter goes inside {% if is_incremental() %} and reads the target as {{ this }}. The merge and delete+insert strategies replace the rows of the window, append duplicates them; microbatch reprocesses whole days, with a lookback; --full-refresh rebuilds.

The trap

WITH fct_events(event_id, occurred_at) AS (VALUES
  (1, TIMESTAMP '2026-06-28 09:00'),
  (2, TIMESTAMP '2026-06-29 18:30'),
  (3, TIMESTAMP '2026-06-30 08:15')),
raw_events(event_id, occurred_at) AS (VALUES
  (2, TIMESTAMP '2026-06-29 18:30'),
  (3, TIMESTAMP '2026-06-30 08:15'),
  (4, TIMESTAMP '2026-06-29 22:10'),  -- late: sent by a phone that was offline
  (5, TIMESTAMP '2026-06-30 11:40'))
SELECT r.event_id, r.occurred_at
FROM raw_events r
WHERE r.occurred_at > (SELECT MAX(occurred_at) FROM fct_events)
ORDER BY r.event_id;
event_idoccurred_at
52026-06-30 11:40:00
Try it in Randori

The fix

WITH fct_events(event_id, occurred_at) AS (VALUES
  (1, TIMESTAMP '2026-06-28 09:00'),
  (2, TIMESTAMP '2026-06-29 18:30'),
  (3, TIMESTAMP '2026-06-30 08:15')),
raw_events(event_id, occurred_at) AS (VALUES
  (2, TIMESTAMP '2026-06-29 18:30'),
  (3, TIMESTAMP '2026-06-30 08:15'),
  (4, TIMESTAMP '2026-06-29 22:10'),  -- late: sent by a phone that was offline
  (5, TIMESTAMP '2026-06-30 11:40'))
SELECT r.event_id, r.occurred_at
FROM raw_events r
WHERE r.occurred_at >= (SELECT MAX(occurred_at) FROM fct_events) - INTERVAL '3 days'
  AND NOT EXISTS (SELECT 1 FROM fct_events f WHERE f.event_id = r.event_id)
ORDER BY r.event_id;
event_idoccurred_at
42026-06-29 22:10:00
52026-06-30 11:40:00
Try it in Randori