DataEng Hub
SilverDelta LakeAbout 30 minutes · sql

Build an SCD Type 2 with MERGE

Apply a day's customer address changes to a dimension table, closing old versions and inserting new ones, in a single MERGE.

Scenario

NorthBridge Retail keeps customer history in dim_customer (SCD Type 2). A daily batch of changed addresses arrives in stg_customer_updates. Apply it: close the current row for changed customers and insert the new version.

Input data

Table: dim_customer

customer_id address valid_from valid_to is_current
C-1 12 MG Road, Pune 2025-01-01 null true
C-2 4 Anna Salai, Chennai 2025-03-10 null true
C-3 9 Brigade Rd, Bengaluru 2025-06-01 null true

Table: stg_customer_updates (effective 2026-10-28)

customer_id address
C-1 88 FC Road, Pune
C-3 9 Brigade Rd, Bengaluru
C-4 2 Park Street, Kolkata
Setup script
CREATE OR REPLACE TABLE dim_customer (
  customer_id STRING, address STRING,
  valid_from DATE, valid_to DATE, is_current BOOLEAN
);
INSERT INTO dim_customer VALUES
  ('C-1', '12 MG Road, Pune',        '2025-01-01', NULL, true),
  ('C-2', '4 Anna Salai, Chennai',   '2025-03-10', NULL, true),
  ('C-3', '9 Brigade Rd, Bengaluru', '2025-06-01', NULL, true);
 
CREATE OR REPLACE TABLE stg_customer_updates (
  customer_id STRING, address STRING
);
INSERT INTO stg_customer_updates VALUES
  ('C-1', '88 FC Road, Pune'),
  ('C-3', '9 Brigade Rd, Bengaluru'),
  ('C-4', '2 Park Street, Kolkata');

Task

  1. C-1 changed address: close its current row (valid_to = '2026-10-28', is_current = false) and insert the new version.
  2. C-3's "update" is identical to the current row: it must cause no change.
  3. C-4 is new: insert it as a current row.
  4. C-2 received no update: untouched.

Expected output

dim_customer after the merge

customer_id address valid_from valid_to is_current
C-1 12 MG Road, Pune 2025-01-01 2026-10-28 false
C-1 88 FC Road, Pune 2026-10-28 null true
C-2 4 Anna Salai, Chennai 2025-03-10 null true
C-3 9 Brigade Rd, Bengaluru 2025-06-01 null true
C-4 2 Park Street, Kolkata 2026-10-28 null true

Constraints

  • A single MERGE statement (a staging CTE/subquery inside its USING is allowed — that's the trick).
  • Re-running the same merge must not create more rows (idempotent for this batch).

Hints

Hint 1

What should the MERGE match on? If you match only on customer_id, how do you both UPDATE the old row and INSERT the new one from a single source row?

Hint 2

Classic trick: union the staged updates twice — once with a join key (to close old rows) and once with a NULL join key (so those rows fall through to WHEN NOT MATCHED and insert the new version).

Hint 3

Filter unchanged rows (C-3) out inside the USING subquery by comparing against the current dimension row — then they never reach the MERGE at all.

Solution

Show solution
-- tested on: Databricks Runtime 15.x LTS
MERGE INTO dim_customer AS t
USING (
  -- rows that will CLOSE an existing current version
  SELECT u.customer_id AS join_key, u.customer_id, u.address
  FROM stg_customer_updates u
  JOIN dim_customer d
    ON d.customer_id = u.customer_id AND d.is_current
  WHERE d.address <> u.address
 
  UNION ALL
 
  -- rows that will INSERT a new version (changed + brand new)
  SELECT NULL AS join_key, u.customer_id, u.address
  FROM stg_customer_updates u
  LEFT JOIN dim_customer d
    ON d.customer_id = u.customer_id AND d.is_current
  WHERE d.customer_id IS NULL OR d.address <> u.address
) AS s
ON t.customer_id = s.join_key AND t.is_current
WHEN MATCHED THEN
  UPDATE SET t.valid_to = DATE'2026-10-28', t.is_current = false
WHEN NOT MATCHED THEN
  INSERT (customer_id, address, valid_from, valid_to, is_current)
  VALUES (s.customer_id, s.address, DATE'2026-10-28', NULL, true);

Explanation

The USING set contains two kinds of rows. Rows with a real join_key match the current dimension row and close it. Rows with join_key = NULL can never match (NULL = anything is false), so they fall into WHEN NOT MATCHED and insert the new version. Unchanged updates (C-3) are filtered out before the merge, which is also what makes a re-run a no-op: after the first run, d.address <> u.address is false for every staged row.

Alternative approaches

  • Two statements (UPDATE then INSERT) inside one transaction — simpler to read, but not atomic on engines without multi-statement transactions; on Delta prefer the single MERGE.
  • dbt snapshots automate exactly this pattern — see the linked article.

Performance notes

Both branches of the UNION join staged rows to the dimension — small-to-big joins that broadcast well. For a large dimension, add a pruning predicate on the target (t.is_current) and consider partitioning or clustering by is_current/key range.

Follow-up questions

  • What changes if deletes must be tracked (customer closes account)?
  • Where does a late update (effective last week) break this design, and what would you do?

Learn the concept

Keep going

ProblemBronze

Deduplicate a raw events table

Keep exactly one row per event_id — the latest by timestamp — from a bronze table that receives replays and retries.