Choosing a Business Key
A MERGE is idempotent only when each incoming row finds the target row that stands for the same real-world thing, or finds nothing. The columns that do the finding are the business key. These are the values that identify a booking, a listing or a guest night, whatever the table's grain is.
| Key kind | Example | Origin | Safe for MERGE when |
|---|---|---|---|
| Natural | `booking_code` | Assigned by the booking app | The source never reuses or reassigns it |
| Surrogate | `booking_key` | Generated by the pipeline | It is computed from the natural key the same way on every run |
| Composite | (`booking_code`, `night_date`) | Several source columns together | The set names a single row at the table's grain |
Natural keys
A natural key comes from the source system, so a rerun sees the same value the first run saw. The risk sits in the source: a key that can change or be reused. An email address fails both ways. Guests change their emails, and someone else can register a closed account's address.
Surrogate keys
A surrogate key is a value the pipeline assigns. Pipelines often use one to replace a long string or to join several sources under a single ID. It goes wrong when the pipeline generates it fresh on each run. If the job calls uuid() and merges on the result, every retry produces keys the table has never seen. Nothing matches, and every row is inserted again.
The fix is a deterministic surrogate: a hash of the natural key. The same booking_code hashes to the same value on every run, so retries and later recomputations land on the rows they already wrote.
SELECT
to_hex(sha256(to_utf8(booking_code))) AS booking_key,
booking_code,
amount_usd
FROM staging_bookingsComposite keys
When a single column cannot name a row, combine several. A table of booked nights holds a row per booking per night. A 3-night stay therefore has 3 rows sharing booking_code, and the key is (booking_code, night_date). Getting the set wrong in either direction makes reruns misbehave. With too few columns, distinct rows collapse onto a single row, and each one overwrites the last. With too many, such as adding updated_at, every change to a booking looks like a new row, and the table grows with every edit.
Enforcing uniqueness
Uniqueness has to hold on both sides of the MERGE. If the target stores a key twice, a single incoming row updates 2 rows. A key can also appear twice in the incoming batch, because the source emitted an update twice or ingestion delivered a file twice. Then the MERGE has 2 candidates for a single target row. Most engines reject the statement. An engine that accepts it has to pick a source row, and a retry may pick the other. Deduplicate the batch before merging, keeping a row per key by a fixed order.
WITH ranked AS (
SELECT
booking_code,
listing_id,
amount_usd,
updated_at,
row_number() OVER (
PARTITION BY booking_code
ORDER BY updated_at DESC, ingest_offset DESC
) AS rn
FROM staging_bookings
)
SELECT
booking_code,
listing_id,
amount_usd,
updated_at
FROM ranked
WHERE rn = 1The second sort column matters. If 2 copies share an updated_at, ordering by that column alone leaves the choice to the engine, and the winner can differ between runs. ingest_offset differs between the copies, so the same row wins every time.
The staging batch holds 2 rows for booking HMX42. They were emitted within the same second, with equal updated_at and different amount_usd. The dedupe orders by updated_at DESC only. What can a rerun do?
- Insert HMX42 twice, since both rows are new to the target
- Keep the other amount, since the engine may break the tie differently
- Fail, since window functions reject equal sort values
- Keep both rows, since row_number() gives ties the same number
SELECT
booking_code,
count(*) AS row_count
FROM dim_booking
GROUP BY booking_code
HAVING count(*) > 1- Do
- Merge on a key that exists in the source before the pipeline touches it
- Hash the natural key when a surrogate is needed
- Deduplicate the batch with a tie-breaking second sort column
- Avoid
- Merge on a uuid() or sequence generated during the run
- Put changing columns like updated_at in the key
- Key on values a person can edit, such as email
dim_booking should hold a row per booking. Its MERGE matches on (booking_code, updated_at). A booking is created on Monday and edited 3 times later that week. How many rows does that booking have by Sunday?
- 1, because the MERGE updates the matching row on every edit
- 2: the first version and the latest version
- 0, because the edits conflict and the MERGE rejects them
- 4, because each edit has a new key and inserts a row
About this lesson
This section is part of the Idempotent Reruns: Intermediate lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.