snowflake
-- EMAIL is NULL on a delete (no after-image), so it must be nullable.
MERGE INTO TARGET_CUSTOMERS t
USING (
SELECT ID, EMAIL, OP, SOURCE_LSN, SEQ FROM STG_CUSTOMERS
QUALIFY ROW_NUMBER() OVER (PARTITION BY ID ORDER BY SOURCE_LSN DESC, SEQ DESC) = 1
) s
ON t.ID = s.ID
WHEN MATCHED AND (s.SOURCE_LSN > t.SOURCE_LSN
OR (s.SOURCE_LSN = t.SOURCE_LSN AND s.SEQ > t.SEQ)) THEN
UPDATE SET EMAIL = s.EMAIL,
IS_DELETED = (s.OP = 'd'),
SOURCE_LSN = s.SOURCE_LSN,
SEQ = s.SEQ
WHEN NOT MATCHED THEN
INSERT (ID, EMAIL, IS_DELETED, SOURCE_LSN, SEQ)
VALUES (s.ID, s.EMAIL, (s.OP = 'd'), s.SOURCE_LSN, s.SEQ);
dedup in the USING subquery keeps one source row per target row; otherwise the result is nondeterministic or the merge errors, depending on ERROR_ON_NONDETERMINISTIC_MERGE. a delete for a key the target has never seen still inserts a marker, so a late older insert cannot create the row.
status: untested on a live Snowflake account.
bigquery
-- staging is partitioned by load time so a scan can be pruned;
-- the target is clustered by key and has no timestamp column at all.
CREATE TABLE `dataset.STG_CUSTOMERS` (
ID INT64, EMAIL STRING, OP STRING,
SOURCE_LSN INT64 NOT NULL, SEQ INT64 NOT NULL,
OP_TS TIMESTAMP, INGESTED_AT TIMESTAMP DEFAULT CURRENT_TIMESTAMP() NOT NULL
)
PARTITION BY DATE(INGESTED_AT)
CLUSTER BY ID;
CREATE TABLE `dataset.TARGET_CUSTOMERS` (
ID INT64, EMAIL STRING, IS_DELETED BOOL NOT NULL,
SOURCE_LSN INT64 NOT NULL, SEQ INT64 NOT NULL
)
CLUSTER BY ID;
MERGE `dataset.TARGET_CUSTOMERS` t
USING (
SELECT ID, EMAIL, OP, SOURCE_LSN, SEQ
FROM (
SELECT ID, EMAIL, OP, SOURCE_LSN, SEQ,
ROW_NUMBER() OVER (PARTITION BY ID ORDER BY SOURCE_LSN DESC, SEQ DESC) AS rn
FROM `dataset.STG_CUSTOMERS`
-- optional pruning, on LOAD time: WHERE DATE(INGESTED_AT) BETWEEN @from_day AND @to_day
)
WHERE rn = 1
) s
ON t.ID = s.ID
WHEN MATCHED AND (s.SOURCE_LSN > t.SOURCE_LSN
OR (s.SOURCE_LSN = t.SOURCE_LSN AND s.SEQ > t.SEQ)) THEN
UPDATE SET EMAIL = s.EMAIL,
IS_DELETED = (s.OP = 'd'),
SOURCE_LSN = s.SOURCE_LSN,
SEQ = s.SEQ
WHEN NOT MATCHED THEN
INSERT (ID, EMAIL, IS_DELETED, SOURCE_LSN, SEQ)
VALUES (s.ID, s.EMAIL, (s.OP = 'd'), s.SOURCE_LSN, s.SEQ);
partition the append-only staging table by DATE(INGESTED_AT) (load time) to prune scans and expire old partitions, and cluster the target by ID for merge performance. window on load time, never on commit time: a change committed on day 1 that reaches staging on day 5 is outside a day-1 commit-date window and would never be merged, leaving the key missing. a commit-date window is only safe if it reaches back past your longest delivery lag. with a load-time window the guard still decides which change wins, so re-merging an overlapping window is harmless. BigQuery raises a runtime error when several source rows match one target row, so keep the dedup.
status: untested on a live BigQuery project.
databricks delta
MERGE INTO target_customers AS t
USING (
SELECT ID, EMAIL, OP, SOURCE_LSN, SEQ
FROM stg_customers
QUALIFY ROW_NUMBER() OVER (PARTITION BY ID ORDER BY SOURCE_LSN DESC, SEQ DESC) = 1
) AS s
ON t.ID = s.ID
WHEN MATCHED AND (s.SOURCE_LSN > t.SOURCE_LSN
OR (s.SOURCE_LSN = t.SOURCE_LSN AND s.SEQ > t.SEQ))
THEN UPDATE SET EMAIL = s.EMAIL,
IS_DELETED = (s.OP = 'd'),
SOURCE_LSN = s.SOURCE_LSN,
SEQ = s.SEQ
WHEN NOT MATCHED
THEN INSERT (ID, EMAIL, IS_DELETED, SOURCE_LSN, SEQ)
VALUES (s.ID, s.EMAIL, (s.OP = 'd'), s.SOURCE_LSN, s.SEQ);
Delta fails the merge with DELTA_MULTIPLE_SOURCE_ROW_MATCHING_TARGET_ROW_IN_MERGE if the source has two rows for a key, so the dedup is required. enable OPTIMIZE + ZORDER BY (ID) on large tables to keep merge fast.
status: untested on a live Databricks workspace.
oracle
-- Oracle has no BOOLEAN column before 23ai, so the marker is NUMBER(1).
-- Debezium sends scn as a STRING ("1513734"); ssn is an int64. Convert once
-- on load: comparing the string would sort '9' after '10'.
INSERT INTO stg_customers (id, email, op, source_scn, seq, op_ts)
SELECT id, email, op, TO_NUMBER(scn), COALESCE(ssn, 0), op_ts
FROM raw_events;
CREATE TABLE target_customers (
id NUMBER(19) PRIMARY KEY,
email VARCHAR2(320),
is_deleted NUMBER(1) DEFAULT 0 NOT NULL CHECK (is_deleted IN (0, 1)),
source_scn NUMBER NOT NULL,
seq NUMBER NOT NULL
);
MERGE INTO target_customers t
USING (
SELECT id, email, op, source_scn, seq
FROM (
SELECT c.id, c.email, c.op, c.source_scn, c.seq,
ROW_NUMBER() OVER (PARTITION BY c.id ORDER BY c.source_scn DESC, c.seq DESC) AS rn
FROM stg_customers c
)
WHERE rn = 1
) s
ON (t.id = s.id)
WHEN MATCHED THEN UPDATE SET
t.email = s.email,
t.is_deleted = CASE WHEN s.op = 'd' THEN 1 ELSE 0 END,
t.source_scn = s.source_scn,
t.seq = s.seq
WHERE s.source_scn > t.source_scn
OR (s.source_scn = t.source_scn AND s.seq > t.seq)
WHEN NOT MATCHED THEN INSERT (id, email, is_deleted, source_scn, seq)
VALUES (s.id, s.email, CASE WHEN s.op = 'd' THEN 1 ELSE 0 END, s.source_scn, s.seq);
the guard sits in the WHERE of the update branch. Oracle also offers DELETE WHERE inside WHEN MATCHED, which would physically remove the row and its stored SCN; that is unsafe under replay, so it is not used. with duplicate source rows Oracle fails with ORA-30926, hence the dedup. an SCN can repeat across changes in one transaction, which is why the ordinal seq (Debezium's ssn, a number) is part of the compare. this card compares (source_scn, seq), which is only valid if ssn is unique per SCN. making sinks bulletproof names rs_id and ssn as the separators for changes that share an SCN, so the full tuple is (source_scn, rs_id, seq): rs_id ("001234.00012345.0124") is a string, so keep it as its own VARCHAR2 column and compare it between source_scn and seq, never as a NUMBER. comparing it as text is correct only if every value is fixed-width, zero-padded, single-case hex under a binary sort (NLS_SORT=BINARY); otherwise split it into numeric parts and compare those. COALESCE(ssn, 0) is defensive: the Debezium Oracle schema marks scn, rs_id and ssn optional, and I did not find a statement about which are absent on snapshot rows; a row with a NULL scn cannot be ordered and should be rejected, not loaded.
status: untested on a live Oracle database.
sql server
-- commit_lsn alone is shared by every change in a transaction, so the
-- compare uses (commit_lsn, change_lsn, event_serial_no). LSNs are
-- BINARY(10): compare as binary, never as text.
-- Snapshot (r) rows can carry NULL change_lsn and event_serial_no. Replace them
-- with the lowest value on load: a snapshot row then sorts before any streamed
-- change that shares its commit_lsn, and a later commit_lsn wins on the first compare.
INSERT INTO dbo.stg_customers (id, email, op, commit_lsn, change_lsn, event_serial_no, op_ts)
SELECT id, email, op,
CONVERT(BINARY(10), REPLACE(commit_lsn_text, ':', ''), 2),
COALESCE(CONVERT(BINARY(10), REPLACE(change_lsn_text, ':', ''), 2),
0x00000000000000000000),
COALESCE(event_serial_no, 0),
op_ts
FROM dbo.raw_events;
CREATE TABLE dbo.target_customers (
id BIGINT NOT NULL PRIMARY KEY,
email NVARCHAR(320) NULL,
is_deleted BIT NOT NULL DEFAULT 0,
commit_lsn BINARY(10) NOT NULL,
change_lsn BINARY(10) NOT NULL,
event_serial_no INT NOT NULL
);
MERGE dbo.target_customers WITH (HOLDLOCK) AS t
USING (
SELECT id, email, op, commit_lsn, change_lsn, event_serial_no
FROM (
SELECT id, email, op, commit_lsn, change_lsn, event_serial_no,
ROW_NUMBER() OVER (
PARTITION BY id
ORDER BY commit_lsn DESC, change_lsn DESC, event_serial_no DESC
) AS rn
FROM dbo.stg_customers
) x
WHERE rn = 1
) AS s
ON t.id = s.id
WHEN MATCHED AND (
s.commit_lsn > t.commit_lsn
OR (s.commit_lsn = t.commit_lsn AND s.change_lsn > t.change_lsn)
OR (s.commit_lsn = t.commit_lsn AND s.change_lsn = t.change_lsn
AND s.event_serial_no > t.event_serial_no)
) THEN
UPDATE SET email = s.email,
is_deleted = CASE WHEN s.op = 'd' THEN 1 ELSE 0 END,
commit_lsn = s.commit_lsn,
change_lsn = s.change_lsn,
event_serial_no = s.event_serial_no
WHEN NOT MATCHED BY TARGET THEN
INSERT (id, email, is_deleted, commit_lsn, change_lsn, event_serial_no)
VALUES (s.id, s.email, CASE WHEN s.op = 'd' THEN 1 ELSE 0 END,
s.commit_lsn, s.change_lsn, s.event_serial_no);
Debezium delivers SQL Server LSNs as strings such as 00000027:00000ac0:0002; the load statement above converts them once (style 2 reads hex without a 0x prefix: 20 hex digits, 10 bytes). verified in the Debezium SQL Server reference: change_lsn, commit_lsn and event_serial_no are optional fields, and its snapshot-flagged example shows change_lsn and event_serial_no as null with commit_lsn set. inferred, not documented: that every snapshot data row looks the same, which is why the load coalesces defensively. a NULL commit_lsn cannot be ordered and should be rejected. MERGE needs the closing semicolon, and HOLDLOCK keeps two concurrent merges from both inserting the same key; Microsoft recommends testing MERGE under your own concurrency, and separate UPDATE/INSERT statements are the alternative.
status: untested on a live SQL Server instance.
postgres
-- pk plus the log position of the change that wrote the row
CREATE TABLE target_customers (
id bigint PRIMARY KEY,
email text,
is_deleted boolean NOT NULL DEFAULT false,
source_lsn bigint NOT NULL,
seq integer NOT NULL
);
-- idempotent upsert; a change applies only if its (source_lsn, seq) is
-- strictly greater than the stored pair
INSERT INTO target_customers AS t (id, email, is_deleted, source_lsn, seq)
SELECT s.id, s.email, (s.op = 'd'), s.source_lsn, s.seq
FROM (
SELECT id, email, op, source_lsn, seq,
ROW_NUMBER() OVER (PARTITION BY id ORDER BY source_lsn DESC, seq DESC) AS rn
FROM stg_customers
) s
WHERE s.rn = 1
ON CONFLICT (id) DO UPDATE
SET email = EXCLUDED.email,
is_deleted = EXCLUDED.is_deleted,
source_lsn = EXCLUDED.source_lsn,
seq = EXCLUDED.seq
WHERE (t.source_lsn, t.seq) < (EXCLUDED.source_lsn, EXCLUDED.seq);
one atomic statement; add RETURNING t.id and a clean replay returns zero rows. ON CONFLICT cannot touch a row twice, so the dedup is required. Postgres 15+ can use MERGE with the same guard (see making sinks bulletproof); ON CONFLICT is the safer choice under concurrent writers. source.lsn is a 64-bit integer in Debezium; if you keep the native pg_lsn type instead, the same comparison works, but never compare LSNs as text (0/9 sorts after 0/10).
status: executed on PGlite (PostgreSQL 18.3 in WebAssembly): out-of-order, duplicate, same-position and delete-then-late-update cases, and a clean replay returned zero rows.
mysql
-- MySQL's position is the binlog file + position, plus the row index
-- (several rows can share one binlog row event). "row" is a reserved word.
CREATE TABLE target_customers (
id BIGINT NOT NULL PRIMARY KEY,
email VARCHAR(320) NULL,
is_deleted BOOLEAN NOT NULL DEFAULT FALSE,
binlog_file VARCHAR(255) NOT NULL,
binlog_pos BIGINT NOT NULL,
row_idx INT NOT NULL
);
-- latest change per id, by the full position
DROP TEMPORARY TABLE IF EXISTS tmp_latest;
CREATE TEMPORARY TABLE tmp_latest AS
SELECT id, email, op, binlog_file, binlog_pos, row_idx
FROM (
SELECT id, email, op, binlog_file, binlog_pos, row_idx,
ROW_NUMBER() OVER (
PARTITION BY id
ORDER BY binlog_file DESC, binlog_pos DESC, row_idx DESC
) AS rn
FROM stg_customers
) x
WHERE rn = 1;
START TRANSACTION;
-- existing rows: only a strictly later position wins (row comparison is lexicographic)
UPDATE target_customers t
JOIN tmp_latest s ON s.id = t.id
SET t.email = s.email,
t.is_deleted = (s.op = 'd'),
t.binlog_file = s.binlog_file,
t.binlog_pos = s.binlog_pos,
t.row_idx = s.row_idx
WHERE (s.binlog_file, s.binlog_pos, s.row_idx) > (t.binlog_file, t.binlog_pos, t.row_idx);
-- keys the target has never seen (a delete inserts a marker)
INSERT INTO target_customers (id, email, is_deleted, binlog_file, binlog_pos, row_idx)
SELECT s.id, s.email, (s.op = 'd'), s.binlog_file, s.binlog_pos, s.row_idx
FROM tmp_latest s
WHERE NOT EXISTS (SELECT 1 FROM target_customers t WHERE t.id = s.id);
COMMIT;
MySQL 8+ is needed for the window function. INSERT ... ON DUPLICATE KEY UPDATE has no WHERE, so a guard would have to be repeated in an IF() per column. the MySQL manual documents that single-table UPDATE assignments are generally evaluated left to right and that multi-table UPDATE gives no guarantee of order; I found no statement about ON DUPLICATE KEY UPDATE. a guard that reads columns an earlier assignment already changed would be fragile. in this card's UPDATE ... JOIN the guard is in the WHERE, which is decided before any assignment, and the assignments read only the staging side, so their order does not matter. binlog file names compare correctly as text only while they keep the same width (mysql-bin.000009 vs mysql-bin.000010). run one applier per table; with several, retry on duplicate-key error 1062. GTIDs are sets, not a total order, and a binlog reset or a failover to another server restarts file names, so add the source_epoch compare from above.
status: untested on a live MySQL server.
redshift
-- staging dedupe (late-events safe): latest by log position
DROP TABLE IF EXISTS stg_dedup;
CREATE TEMP TABLE stg_dedup DISTKEY(id) SORTKEY(id) AS
SELECT id, email, op, source_lsn, seq
FROM (
SELECT id, email, op, source_lsn, seq,
ROW_NUMBER() OVER (PARTITION BY id ORDER BY source_lsn DESC, seq DESC) AS rn
FROM stg_customers
) x
WHERE rn = 1;
BEGIN;
-- existing rows: only a strictly later position wins
UPDATE target_customers
SET email = s.email,
is_deleted = (s.op = 'd'),
source_lsn = s.source_lsn,
seq = s.seq
FROM stg_dedup s
WHERE target_customers.id = s.id
AND (s.source_lsn > target_customers.source_lsn
OR (s.source_lsn = target_customers.source_lsn AND s.seq > target_customers.seq));
-- keys the target has never seen (a delete inserts a marker)
INSERT INTO target_customers (id, email, is_deleted, source_lsn, seq)
SELECT s.id, s.email, (s.op = 'd'), s.source_lsn, s.seq
FROM stg_dedup s
LEFT JOIN target_customers t ON t.id = s.id
WHERE t.id IS NULL;
COMMIT;
Redshift's MERGE takes no AND condition on its WHEN clauses, so the guard cannot sit there. it can be pushed into the USING subquery (join the target and keep only rows that are newer or have no target match), but UPDATE ... FROM plus INSERT in one transaction is the form used here: the guard is explicit and the source never references the target. Redshift does not enforce primary keys, so run one writer per table or two appliers can insert the same key. consider VACUUM / ANALYZE schedules on heavy churn tables.
status: untested on a live Redshift cluster.
handling hard parts
1) replays after a crash
there is nothing to undo first. re-load the staging rows you doubt and run the same merge again: a change that was already applied has the same (SOURCE_LSN, SEQ) as the stored pair, so the strict comparison skips it, and anything the crash lost is applied. choose how far back to reload by consumer progress (rewind the consumer group, or re-read the landed files) or by log position; a clock-time window only decides how much to re-read, never which change wins.
-- Postgres. stg_archive is the append-only landing history.
-- reload window: it starts at a position you trust, inclusive. re-reading a
-- change is harmless; this is not the apply guard, which stays strict.
INSERT INTO stg_customers (id, email, op, source_lsn, seq, op_ts)
SELECT id, email, op, source_lsn, seq, op_ts
FROM stg_archive
WHERE source_lsn >= 4294967296;
-- then re-run the regular upsert above, unchanged
2) keyless tables
avoid “replica identity full” targets. pick a natural business key or synthesize one (hash of stable columns). worst case, land to a history table only. a key change is a delete of the old key plus an insert of the new one, so the ordering guarantee does not span it.
3) deletes: markers first, purge later
the cards above never run a DELETE: a delete event becomes IS_DELETED = true with its position. readers use a view that hides the markers.
-- Postgres. readers never see markers
CREATE VIEW customers AS
SELECT id, email FROM target_customers WHERE NOT is_deleted;
-- physical delete (purge), the only one on this page: it is safe only for
-- markers older than anything that can still be replayed. set the bound from
-- your topic and archive retention, and from any re-snapshot you might run.
DELETE FROM target_customers
WHERE is_deleted AND source_lsn < 8589934592;
the cost of markers is storage and a retention policy. if you must erase personal data, null the payload columns in the same update that sets the marker; keep the key and the position.
4) schema evolution
additive columns are easiest: default target to NULL and include them in the UPDATE SET. for type changes, land to a compatible staging column and cast during merge.
5) where timestamps still belong
OP_TS answers “when”, not “which one is newer”. use it to partition and prune the staging table, to expire old staging data, to bound a reload (by load time, not commit time, or late arrivals fall outside the window), and to report freshness. never use it to rank two changes to the same row, and never as the WHEN MATCHED condition.