SQL templates you can adapt
Snowflake MERGE
-- staging.orders_src must already be deduped to ONE row per order_id
-- (latest by log position, e.g. LSN/SCN) before this MERGE runs.
-- Deletes are kept as delete markers (deleted = TRUE plus the delete's
-- position), so a replayed older update cannot resurrect the row. Readers
-- filter deleted = FALSE; amount/status are NULL on a delete, so those
-- columns must be nullable. Assumes src.lsn is unique per change for a key;
-- if it can repeat, compare the (lsn, seq) pair as in /partitioning/#recon.
-- If you add source_lsn to an existing table, backfill it first: a NULL
-- source_lsn makes tgt.source_lsn < src.lsn NULL, so the row is silently
-- never updated. Or compare COALESCE(tgt.source_lsn, -1) < src.lsn.
MERGE INTO analytics.orders tgt
USING staging.orders_src src
ON tgt.order_id = src.order_id
WHEN MATCHED AND tgt.source_lsn < src.lsn THEN UPDATE SET
amount = src.amount,
status = src.status,
deleted = (src.op = 'd'),
source_lsn = src.lsn,
processed_ts_ms = src.ts_ms -- metric only, never used for ordering
WHEN NOT MATCHED THEN
INSERT (order_id, amount, status, deleted, source_lsn, processed_ts_ms)
VALUES (src.order_id, src.amount, src.status, (src.op = 'd'), src.lsn, src.ts_ms);
Untested: not run in Snowflake (the guard logic was run as PostgreSQL MERGE).
Why source_lsn and a delete marker, and what makes a position safe to compare:
Making Sinks Bulletproof.
BigQuery change-applier
-- Full rebuild from the retained event history in staging. The delete is kept
-- as a delete marker (deleted = TRUE plus its position), exactly as in the
-- incremental targets above and below, so readers filter deleted = FALSE and
-- nothing that later re-applies older events can resurrect a deleted key.
-- amount/status are NULL on a delete, so those columns must be nullable.
CREATE OR REPLACE TABLE analytics.orders AS
SELECT
order_id,
amount,
status,
(op = 'd') AS deleted,
lsn AS source_lsn
FROM (
SELECT *,
-- order by log position (authoritative commit order); seq is the
-- within-transaction ordinal for changes that share a position
ROW_NUMBER() OVER (PARTITION BY order_id ORDER BY lsn DESC, seq DESC) AS rnk
FROM staging.orders_src
)
WHERE rnk = 1;
Untested: not run against a live BigQuery project. Check it against your own schema before use.
dbt incremental model
-- models/orders.sql. Written for Snowflake, BigQuery and PostgreSQL 15+
-- adapters that support incremental_strategy='merge'. The target needs
-- order_id, amount, status (nullable), deleted and source_lsn (never NULL).
{{
config(
materialized='incremental',
incremental_strategy='merge',
unique_key='order_id'
)
}}
with source_events as (
select order_id, amount, status, op, lsn, seq
from {{ source('cdc', 'orders') }}
{% if is_incremental() %}
-- Bound the scan by the source log position already applied. It is >=, not >:
-- re-reading the changes at the high-water position is harmless (the guard
-- below drops them) and keeps a different key's change that shares that
-- position. The same key at the same lsn is dropped by the strict guard, so
-- if one key can have two changes at one position, store the ordinal and
-- compare the pair. A strict
-- bound is not safe if changes can land in this table out of order: the
-- late row has a lower lsn than max(source_lsn) and is skipped for good.
-- var('lsn_lookback') subtracts a margin (default 0) to re-read further back.
where lsn >= (
select coalesce(max(source_lsn), 0) - {{ var('lsn_lookback', 0) }}
from {{ this }}
)
{% endif %}
),
ranked as (
select order_id, amount, status, op, lsn,
-- order by log position (authoritative); seq is the within-transaction
-- ordinal for changes that share a position
row_number() over (
partition by order_id
order by lsn desc, seq desc
) as rnk
from source_events
),
latest as (
select order_id, amount, status, op, lsn
from ranked
where rnk = 1
)
-- The delete is not filtered out here. It becomes a delete marker row:
-- deleted = true plus the delete's position, so a replayed older update
-- cannot bring the key back. Readers filter deleted = false.
select
l.order_id,
l.amount,
l.status,
(l.op = 'd') as deleted,
l.lsn as source_lsn
from latest l
{% if is_incremental() %}
-- The version guard. Keep a change only if the key is new or the change is
-- later in the log than the row already stored. A replay carries the same
-- position it had the first time, so it is dropped here.
left join {{ this }} t
on t.order_id = l.order_id
where t.order_id is null
or t.source_lsn < l.lsn
{% endif %}
Untested: not run against a live warehouse. Two limits to know. The guard is evaluated
before dbt issues the merge, so it assumes one run at a time per model (two concurrent runs
can race). It also assumes lsn is a single number that is unique per change for a key;
if it can repeat, or is a tuple (MySQL file and position, SQL Server LSNs), store the ordinal
alongside it and compare the pair as in
Making Sinks Bulletproof, and bound on
a loader-assigned load id instead of lsn. Do not use
incremental_predicates for the guard: it goes into the merge’s
ON clause, so a row that fails it is treated as new and inserted again.
Keep history when you need it
- Add
valid_from and valid_to columns around each change.
- Close the previous version when a new update arrives.
- Expose current rows via a view that filters on
valid_to IS NULL.
This pattern powers SCD Type 2 tables without losing the benefits of CDC
freshness.