1. Freeze the input batch
Use a stable batch ID and a reproducible source snapshot. Order duplicate source records by event time and a unique ingestion sequence. Keep exactly one row per key before running MERGE.
2. Protect newer data
MERGE INTO customer_segments AS target
USING deduplicated_batch AS source
ON target.customer_id = source.customer_id
WHEN MATCHED AND source.version > target.version
THEN UPDATE SET segment = source.segment, version = source.version
WHEN NOT MATCHED
THEN INSERT (customer_id, segment, version)
VALUES (source.customer_id, source.segment, source.version);
This example assumes the target already has one row per customer and versions increase for each customer. Check both assumptions at ingestion.
3. Replay the batch
Run the same batch twice on a test table and compare the resulting rows. Test a late older record and a batch with duplicate source keys. Record inserted and updated counts from table history.