Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 109/ 160
06. Database Design, Normalization & Semi-Structured SQL

Slowly Changing Dimensions (SCD Type 1 & Type 2) in SQL

Overwrite history (Type 1) or version attributes (Type 2) for changing dims.

AdvancedSCD1 · SCD2 · History3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

When something changes, either overwrite it (no history) or keep the old version and add a new one with dates (full history).

Think of it like…

Type 1 is correcting your address in a contacts app: the old one is gone. Type 2 is a passport's stamp history: every past entry stays, and you can always see where someone lived at any date.

Where you’ve seen it

A customer moves from Pune to Bengaluru in June. With Type 2, dim_customer has two rows for them: (key 101, Pune, valid until 2026-06-01) and (key 245, Bengaluru, current). Orders before June point to key 101, so a "revenue by city" report still credits those sales to Pune.

Words you’ll hear

Type 1
Overwrite: the dimension always shows the latest value; history is lost.
Type 2
New row per change, with valid_from, valid_to and an is_current flag.
Surrogate key
Warehouse-generated key per version, used by fact rows.
Natural / business key
The source system's id (customer_id), shared by all versions.

Visual diagram

Loading interactive diagram

Theory & example queries

Type 1 vs Type 2

Type 1 is a plain UPDATE: fix a typo in a name or refresh an attribute where history doesn't matter. Every past fact now reports the new value, which is right for corrections and wrong for real changes the business analyses over time.

Type 2 keeps every version: each row has a surrogate key, the business key, the attributes, valid_from, valid_to (NULL or a far-future date for the current row) and often is_current. When an attribute changes, close the current row and insert a new one. You can mix them per column: overwrite email (Type 1) but version city and segment (Type 2).

Applying a Type 2 changeQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1BEGIN;23UPDATE dim_customer4SET5  valid_to = '2026-06-01',6  is_current = FALSE7WHERE8  customer_id = 79  AND is_current;1011INSERT INTO12  dim_customer (13    customer_id,14    city,15    valid_from,16    valid_to,17    is_current18  )19VALUES20  (21    7,22    'Bengaluru',23    '2026-06-01',24    NULL,25    TRUE26  );2728COMMIT;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Start transaction

Open a transaction so changes can be checked and committed or rolled back together.

1/28
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative transaction status
BEGIN UPDATE 1 INSERT 0 1 COMMIT

Note: Assumes customer 7 has one current row when the Type 2 change is applied.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Type 1 overwrites; Type 2 closes the old row and adds a new version.

Joining facts to the right version

The cleanest approach is to look up the current surrogate key when each fact is loaded and store it on the fact row, so later joins are a simple key equality and historical reports automatically use the right version.

If facts only carry the business key, join on it plus the date range: ON d.customer_id = f.customer_id AND f.order_date >= d.valid_from AND (f.order_date < d.valid_to OR d.valid_to IS NULL). Use half-open ranges (>= from, < to) so a change date never matches two versions, and add a unique constraint so only one row per customer can be current.

Only one current row per customerQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1CREATE UNIQUE INDEX ON dim_customer (customer_id)2WHERE3  is_current;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/3
3OutputInspect the representative rows, affected-row count, plan, or command status.
Successful index creation
CREATE INDEX

Note: The command succeeds only if there is at most one current row per customer in the existing data.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Store the version's surrogate key on facts, or join with half-open date ranges.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Design

Decide per attribute

Decide which attributes need history (city, segment, plan) and which can be overwritten (typo fixes, email).

Focus at this step

city → Type 2 · email → Type 1

What to watch at this step
Ask
will we report on the old value?
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

A slowly changing dimension (SCD) is a dimension whose attributes change occasionally, like a customer moving city. Type 1 overwrites the old value, keeping no history. Type 2 keeps history by closing the current row (setting valid_to) and inserting a new row with a new surrogate key, so past facts still link to the version that was true at the time. Other types exist (Type 3 keeps a "previous value" column), but 1 and 2 are the ones used most.

Why it matters: "Revenue by customer city last year" gives different answers depending on whether moves overwrite history. Getting SCDs right is central to data warehousing, and it's one of the most common data engineering interview topics, often asked as "how would you track a customer's address changes?"

When to reach for it

  • Customer, product and employee dimensions in a warehouse
  • Reporting on attributes as they were at the time of each event
  • Data engineering interview designs

When to avoid or be careful

  • Type 1 for attributes the business analyses historically
  • Overlapping or gapped valid_from / valid_to ranges
  • Joining facts to dimensions on the business key alone when the dimension is Type 2

SCD Type 1 vs Type 2 vs Type 3

Type 1 (overwrite)
Best for: Corrections and attributes where history doesn't matter

Strengths: Simple; one row per entity.

Watch out: History is lost; old reports change.

Type 2 (new row per version)
Best for: Attributes analysed over time: city, segment, plan

Strengths: Full history; facts report as of the time they happened.

Watch out: More rows, surrogate keys and more complex loading.

Type 3 (previous-value column)
Best for: Comparing only the current and immediately previous value

Strengths: Simple "before and after" analysis.

Watch out: Only one level of history.

Interview signals & numbers to know

When this topic comes up

  • “Track customers' address changes”
  • “Revenue by the region the customer was in at the time”
  • SCD Type 2
  • valid_from / valid_to
  • dbt snapshots

Benchmarks & rules of thumb

2 -
most common types: 1 and 2
1 -
current row per business key in Type 2
>= from, < to -
half-open validity ranges

Common mistakes & follow-ups

Common interview mistakes

  • Joining facts to a Type 2 dimension on customer_id alone, which duplicates every fact once per version.
  • Using inclusive valid_to dates so a change date matches two versions.
  • Closing the old row and inserting the new one in separate transactions, leaving a moment with no current row.

Likely interviewer follow-ups

  • How would you implement SCD Type 2 with a MERGE statement?
  • How do you join facts to the correct dimension version?
  • When is Type 1 the right choice?
Interview tip: Use the customer-moving-city example, show the two rows with dates, and explain how old orders keep pointing at the old version. That one example covers the whole concept.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Slowly Changing Dimensions (SCD Type 1 & Type 2) in SQL with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Star Schema & Snowflake Schema Design for Analytics
Next topic
Views: Creating Virtual Tables for Security & Simplicity