How do you implement Slowly Changing Dimension (SCD) Type 2 in Databricks?
1Times asked
Sep 2026Last seen
Sep 2026First seen
💡 Model Answer
SCD Type 2 tracks historical changes by creating a new record for each change and keeping the old record. In Databricks you typically use Delta Lake to store the dimension table. The steps are:
- Schema: Add columns
effective_start,effective_end, andis_currentto the dimension table. - Merge: When new source data arrives, perform a
MERGE(upsert) against the Delta table. For each source row, compare the key and the business attributes. If the key exists and any attribute has changed, setis_currentto false andeffective_endto the current timestamp for the existing row, then insert a new row with the new attributes,effective_startas the current timestamp,effective_endas a sentinel (e.g.,9999-12-31), andis_currenttrue. - Idempotency: Use the
MERGEcondition on the key and the business attributes to avoid duplicate inserts. - Querying: To get the current view, filter
is_current = true. To get history, query the full table.
Example Delta Lake SQL:
sql
MERGE INTO dim_customer tgt
USING source src
ON tgt.customer_id = src.customer_id
WHEN MATCHED AND (tgt.name <> src.name OR tgt.address <> src.address) THEN
UPDATE SET tgt.is_current = false, tgt.effective_end = current_timestamp()
WHEN NOT MATCHED THEN
INSERT (customer_id, name, address, effective_start, effective_end, is_current)
VALUES (src.customer_id, src.name, src.address, current_timestamp(), '9999-12-31', true);This approach ensures that every change is captured with its own row, preserving history while keeping the current state easily queryable.
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.
Get Assisting AI — Starts at ₹500