Hello! Welcome back to your course on practical data architecture.
In our last lesson, we created the gold layer of our medallion architecture, preparing aggregated data for business analytics. However, a crucial aspect of data warehousing is managing how data changes over time. What happens when a customer moves, a product is renamed, or a sales territory is reorganized? Simply overwriting the old data can erase valuable historical context.
Today, we'll address this challenge head-on. Your learning outcome is to explain the purpose of Slowly Changing Dimensions (SCDs) and implement an SCD Type 2 update using Delta Lake. This is a cornerstone technique for any data architect building analytical systems that require historical accuracy.
1. The "Why": Understanding Slowly Changing Dimensions
In data warehousing, a "dimension" is a table that describes your business entities—customers, products, locations, etc. These dimensions provide the context for your facts (like sales transactions). While some attributes of these dimensions change frequently (like a stock price), many change infrequently, or "slowly."
The way you handle these changes has major implications for historical reporting.
- SCD Type 1 (Overwrite): You simply update the record in place. This is easy, but you lose all history. If a customer moves from New York to California, a Type 1 update makes it look like all their past purchases happened while they lived in California, which is incorrect.
- SCD Type 2 (Add a New Row): This is the most common and powerful method. Instead of overwriting, you preserve history by:
- "Expiring" the current record (e.g., setting an
is_currentflag tofalseand populating anend_date). - Inserting a new record with the updated attributes, marking it as the current version (e.g.,
is_current = trueand setting astart_date).
- "Expiring" the current record (e.g., setting an
This ensures that transactions are always linked to the correct version of the dimension at that point in time.
The image below shows this process. When the product description for Product ID 010 changes, the old record is end-dated, and a new, active record is created with the updated description.

To deepen your understanding, let's hear from the experts at Databricks.
Tech Chat | Slowly Changing Dimensions (SCD) Type 2
The 'Tech Chat' from Databricks provides an excellent conceptual introduction to SCD Type 2, explaining its importance in the context of Kimball's dimensional modeling and why it's a fundamental pattern.
Watch from 03:55 to 11:40. The speakers will define SCD Type 2, contrast it with Type 1, and explain its crucial role in enabling historical, 'as-of' analysis.
2. The Architectural Shift: From Hadoop's Challenge to Delta Lake's Solution
From your perspective as an enterprise architect, it's useful to understand why implementing SCD Type 2 on a data lake was historically difficult.
Traditional big data storage like HDFS or standard cloud object storage (S3, ADLS) is based on immutable, append-only files. Performing an UPDATE to expire an old record was not a native operation. It often required complex and inefficient workarounds, such as rewriting entire partitions of data.
Delta Lake changes the game with ACID transactions and the MERGE command.
The MERGE INTO statement (also known as an "upsert") allows you to atomically perform a combination of INSERT, UPDATE, and DELETE operations in a single statement. This is the key that unlocks efficient and reliable SCD implementations directly on your data lake.
Tech Chat | Slowly Changing Dimensions (SCD) Type 2
Let's return to the Databricks 'Tech Chat' video. The speakers now discuss how Delta Lake's features, specifically the MERGE operator, solve the challenges of implementing SCDs on a data lake.
Watch from 17:15 to 18:55. Focus on how the speakers describe the difficulty of performing updates on append-only systems and how the transactional MERGE operator in Delta Lake provides the solution.
3. Implementing an SCD Type 2 Pipeline
Now for the practical part. We will walk through the logic of implementing an SCD Type 2 update using PySpark and Delta Lake's merge() API. This is a very common and robust pattern in modern data pipelines.
We'll follow a clear, step-by-step approach that is excellently demonstrated in the following video. The core idea is to cleverly construct a source DataFrame that, when used in the merge operation, will handle both expiring old records and inserting new ones.
61. Databricks | Pyspark | Delta Lake : Slowly Changing Dimension (SCD Type2)
This video from 'Raja's Data Engineering' provides one of the clearest step-by-step explanations of the logic for an SCD Type 2 implementation in PySpark. He first illustrates the concept with an Excel sheet before diving into the code.
Watch from 02:48 to 11:59. Pay close attention to the logic of how he joins the source and target, filters for changes, and then uses a union to create a special staging dataset with a 'merge_key'. This is the core of the pattern.
Let's break down that logic into concrete steps you'd write in a notebook.
Assume you have:
target_table: Your existing Delta dimension table (e.g.,customers).source_df: A Spark DataFrame with the latest batch of data from your source system.
Step 1: Identify Changed and New Records
First, join your incoming source_df with the target_table on the natural key (e.g., customer_id) to find what's new or what has changed.
# Select only the current-ly active records from the target Delta table
target_current_df = target_table.toDF().where("is_current = True")
# Left-join source to target to find matches
# We alias target columns to avoid name collisions
joined_df = source_df.join(
target_current_df.alias("tgt"),
source_df.customer_id == col("tgt.customer_id"),
"left"
)
# Filter for records that are new (no match in target) OR have changed attributes
# Using a hash function is an efficient way to compare many columns at once
changed_records_df = joined_df.where(
"tgt.customer_id IS NULL OR " +
"hash(source_df.address, source_df.email) != hash(tgt.address, tgt.email)"
).select(source_df["*"]) # Select only the source columns for the new/updated versions
Step 2: Prepare the Staging DataFrame for MERGE
This is the clever part of the pattern. We need to perform two actions: UPDATE existing rows in the target, and INSERT new rows. We can stage the data for this in a single DataFrame using a UNION.
# Staging for Inserts: These are the new and updated records from the source.
# We add columns to match the target schema.
inserts_df = changed_records_df.withColumn("is_current", lit(True)) \
.withColumn("start_date", current_timestamp()) \
.withColumn("end_date", lit(None).cast("timestamp"))
# Staging for Updates: These are the records in the target that need to be expired.
# We create a DataFrame to match these records and set their 'is_current' to False.
# The 'mergeKey' will be used to find these records in the target table.
updates_df = changed_records_df.alias("src").join(
target_current_df.alias("tgt"),
col("src.customer_id") == col("tgt.customer_id")
).select(
col("tgt.*") # Select all columns from the old target record
).withColumn("is_current", lit(False)) \
.withColumn("end_date", current_timestamp())
# Union the two sets together. This is the DataFrame we will merge.
staging_df = inserts_df.unionByName(updates_df)
Step 3: Execute the MERGE Operation
Now, you can execute the merge operation. You'll merge your staging_df into the target Delta table. The merge condition will match records on their surrogate key (or a composite key if one isn't available).
# Assuming target_table is a DeltaTable object
target_table.alias("tgt").merge(
staging_df.alias("stg"),
"tgt.customer_sk = stg.customer_sk" # customer_sk is a surrogate key
).whenMatchedUpdateAll().whenNotMatchedInsertAll().execute()
The logic here is that:
- Records staged for update (the old versions) will find a match in the target table on their key, and
whenMatchedUpdateAll()will update them tois_current = Falsewith a newend_date. - Records staged for insert (the new versions) will not yet exist in the target table, so
whenNotMatchedInsertAll()will insert them as new, active records.
This pattern is powerful because it's idempotent—running it multiple times with the same source data won't create duplicate history.
Test your understanding!
In the MERGE logic above, we staged two types of records into staging_df: those for INSERT and those for UPDATE. Why do we need to do this UNION? Why can't we just use a simpler MERGE statement with one WHEN MATCHED clause to expire old records and one WHEN NOT MATCHED clause to insert new ones?
Show answer
A standard MERGE compares a source to a target. If we only used the incoming data as our source:
WHEN MATCHEDwould find an existing customer. We could update it tois_current = False. But how would we insert the new version of that same customer? TheMERGEstatement doesn't have a clause to both update the matched row AND insert a new one based on the source.WHEN NOT MATCHEDwould correctly insert brand-new customers.
By pre-staging a UNION of both the records to be inserted and the records to be updated, we create a single source DataFrame (staging_df) that can drive both actions cleanly within a single, transactional merge operation.
Conclusion
Mastering the SCD Type 2 pattern is a significant step in your journey to becoming a data architect. You now understand not just the "how" of its implementation with modern tools like Delta Lake, but also the critical "why" behind its importance for maintaining data integrity and historical accuracy in an analytical system.
Key Takeaways:
- SCDs are techniques for managing changes in dimension data over time.
- SCD Type 2 is the most common approach, preserving history by expiring old records and inserting new ones. This is essential for accurate point-in-time analysis.
- Implementing SCD Type 2 was challenging on traditional data lakes due to immutable files.
- Delta Lake's
MERGEcommand provides the transactional capability to perform the necessary inserts and updates atomically, making SCD Type 2 on the data lake efficient and reliable. - A common implementation pattern in PySpark involves creating a staging DataFrame with a
UNIONof records to be inserted and records to be updated, which then drives theMERGEoperation.
In our next lesson, we will explore another crucial aspect of building robust data pipelines: implementing a high-watermark incremental load. This technique allows you to efficiently process only new or updated data in each batch run, saving significant time and computational resources.