The goal
You need a dimension that keeps history: when a customer moves city, the old row is closed and a new current row is opened. Lakeflow AUTO CDC ... STORED AS SCD TYPE 2 does this for you inside a pipeline. Many teams still run it as a plain notebook or SQL job, though, and the hand-written MERGE is where things go wrong. You end up with two current rows per key, history that vanishes on rerun, or every row closed because the source extract was empty.
This post gives one MERGE that closes and opens rows in a single atomic commit, is safe to rerun, and comes with the checks to prove it.
Table design
CREATE TABLE IF NOT EXISTS main.gold.dim_customer (
customer_sk BIGINT GENERATED ALWAYS AS IDENTITY,
customer_id STRING NOT NULL,
name STRING,
city STRING,
segment STRING,
row_hash STRING NOT NULL,
valid_from TIMESTAMP NOT NULL,
valid_to TIMESTAMP,
is_current BOOLEAN NOT NULL
)
CLUSTER BY (customer_id);
| Column | Purpose |
|---|---|
customer_id | Business key from the source |
row_hash | Hash of the tracked attributes, so change detection is one comparison |
valid_from / valid_to | The interval the version was true. valid_to is NULL on the current row |
is_current | Lets the MERGE and the reports filter to one row per key cheaply |
Warning
An identity column disables concurrent transactions on the table. That is fine for a single nightly writer, but if anything else writes to the dimension at the same time, use a deterministic hash key instead of
customer_sk.
Step 1: stage and deduplicate the source
MERGE fails with DELTA_MULTIPLE_SOURCE_ROW_MATCHING_TARGET_ROW_IN_MERGE if two source rows match one target row. Deduplicate first, and compute the hash once:
CREATE OR REPLACE TEMP VIEW staged AS
SELECT
customer_id,
name,
city,
segment,
sha2(concat_ws('||',
coalesce(name, '<null>'),
coalesce(city, '<null>'),
coalesce(segment, '<null>')), 256) AS row_hash,
change_ts AS effective_ts
FROM main.silver.customer_changes
WHERE change_ts > :watermark
QUALIFY row_number() OVER (PARTITION BY customer_id ORDER BY change_ts DESC) = 1;
Tip
concat_wsskips NULLs, so('A', NULL)and(NULL, 'A')would hash the same without thecoalesce. Always wrap tracked columns in a sentinel before hashing.
Keeping only the latest change per key drops intermediate versions within one batch. If you need every intermediate version, run the MERGE once per change sequence or use AUTO CDC with a sequencing column.
Step 2: the staged-updates MERGE
A single MERGE can't both update a target row and insert a new version of the same key from the same source row. The standard trick is to feed changed keys twice:
- once with
merge_key = customer_id, which matches the current row so it gets closed; - once with
merge_key = NULL, which matches nothing, so it gets inserted as the new current version.
MERGE INTO main.gold.dim_customer AS t
USING (
-- New keys and changed keys: match on the business key
SELECT s.customer_id AS merge_key, s.*
FROM staged s
UNION ALL
-- Changed keys only: NULL key forces an insert of the new version
SELECT NULL AS merge_key, s.*
FROM staged s
JOIN main.gold.dim_customer d
ON s.customer_id = d.customer_id
AND d.is_current = true
WHERE d.row_hash <> s.row_hash
AND s.effective_ts > d.valid_from
) AS u
ON t.customer_id = u.merge_key AND t.is_current = true
WHEN MATCHED AND t.row_hash <> u.row_hash AND u.effective_ts > t.valid_from THEN
UPDATE SET t.is_current = false,
t.valid_to = u.effective_ts
WHEN NOT MATCHED THEN
INSERT (customer_id, name, city, segment, row_hash, valid_from, valid_to, is_current)
VALUES (u.customer_id, u.name, u.city, u.segment, u.row_hash, u.effective_ts, NULL, true);
Why each part matters:
| Clause | What it prevents |
|---|---|
t.is_current = true in ON | Historical rows never match, so they are never touched |
t.row_hash <> u.row_hash | Unchanged rows produce no rewrite and no new version |
u.effective_ts > t.valid_from | Late, out-of-order events can't close a newer version |
merge_key = NULL branch only for changed rows | New keys are inserted once, not twice |
Why it is safe to rerun
Run the same batch twice. On the second run the current row already carries the new hash. The MATCHED condition is false, the NULL branch finds no hash difference, and the matched-key rows hit the current row, so nothing is inserted. The second commit changes nothing. Check operationMetrics to confirm:
DESCRIBE HISTORY main.gold.dim_customer LIMIT 1;
-- operationMetrics: numTargetRowsInserted = 0, numTargetRowsUpdated = 0 on a rerun
Step 3: handle rows deleted at the source
If the source sends a full snapshot every run, keys missing from the snapshot were deleted. WHEN NOT MATCHED BY SOURCE (Databricks Runtime 12.2 LTS and later) closes them in the same commit. Add it to the MERGE above:
WHEN NOT MATCHED BY SOURCE AND t.is_current = true THEN
UPDATE SET t.is_current = false,
t.valid_to = current_timestamp()
Caution
NOT MATCHED BY SOURCEtreats every current row that is absent from the source as deleted. If the extract is empty or partial (a failed upstream job, a filtered watermark view), this closes the whole dimension in one commit. Only use it with full snapshots, and guard it with a row-count check before the MERGE.
A simple guard in Python before the MERGE:
snap = spark.table("staged").count()
cur = spark.sql(
"SELECT count(*) AS c FROM main.gold.dim_customer WHERE is_current"
).first()["c"]
if cur > 0 and snap < cur * 0.9:
raise ValueError(f"Snapshot has {snap} rows vs {cur} current; refusing to close rows")
For incremental (CDC) sources, don't use NOT MATCHED BY SOURCE. Carry an explicit operation column instead and close rows where op = 'D' with a separate WHEN MATCHED AND u.op = 'D' clause placed before the change clause.
Step 4: validate after every run
Run these as the last task of the job and fail the job if any returns rows.
More than one current row per key:
SELECT customer_id, count(*) AS current_rows
FROM main.gold.dim_customer
WHERE is_current
GROUP BY customer_id
HAVING count(*) > 1;
Overlapping or broken intervals:
SELECT customer_id, valid_from, valid_to, next_from
FROM (
SELECT customer_id, valid_from, valid_to,
lead(valid_from) OVER (PARTITION BY customer_id ORDER BY valid_from) AS next_from
FROM main.gold.dim_customer
)
WHERE next_from IS NOT NULL
AND (valid_to IS NULL OR valid_to <> next_from);
Current rows with a closed interval (or the reverse):
SELECT count(*) FROM main.gold.dim_customer
WHERE (is_current AND valid_to IS NOT NULL)
OR (NOT is_current AND valid_to IS NULL);
Symptom, cause, fix
| Symptom | Likely cause | Fix |
|---|---|---|
| Two current rows for one key | Source not deduplicated, or two writers ran at once | Deduplicate in staged; stop concurrent runs (max concurrent runs = 1) |
DELTA_MULTIPLE_SOURCE_ROW_MATCHING_TARGET_ROW_IN_MERGE | Duplicate keys in the source | QUALIFY row_number() ... = 1 |
| New version inserted on every run | Hash includes a volatile column (load timestamp, file name) | Hash only the tracked business attributes |
| Whole dimension closed overnight | Empty snapshot with NOT MATCHED BY SOURCE | Row-count guard; RESTORE TABLE ... TO VERSION AS OF the previous version |
| Old value became current again | Late event closed a newer row | effective_ts > valid_from conditions |
| MERGE slows down every month | Full scan of history to find current rows | Cluster by the business key; keep is_current in the ON clause |
If a bad run did land, roll it back from Delta history:
DESCRIBE HISTORY main.gold.dim_customer;
RESTORE TABLE main.gold.dim_customer TO VERSION AS OF 412;
Prevent it next time
- Set the job's maximum concurrent runs to 1 so the dimension has exactly one writer.
- Keep the row-count guard and the three validation queries in the job, not in a runbook.
- Store the watermark in a control table and update it only after validation passes.
- Review
operationMetricsinDESCRIBE HISTORYweekly. A sudden jump innumTargetRowsUpdatedusually means the hash definition or the source changed. - If the table grows large, check that MERGE prunes by the clustering key rather than scanning all history.
Get the weekly HubDatAI email
One email a week with everything new: posts, learning sessions and videos. Free, no spam, unsubscribe in one click. What you get