
In Data Engineering and Analytics Engineering interviews, few topics expose warehouse modeling gaps faster than Slowly Changing Dimensions (SCDs). Rather than asking for textbook definitions, interviewers open a shared SQL editor and present a real reporting failure: "Finance noticed that Q1 2025 Enterprise ARR shifts every morning whenever an existing customer upgrades or downgrades today. Someone built dim_customers by overwriting plan_tier in place. How do you redesign this dimension, write the SQL to reconstruct versioned history from raw events, and prevent double-counting when date intervals overlap?"
Candidates who simply answer "add updated_at and join with BETWEEN" quickly stumble on follow-up traps around boundary collisions, no-op updates, idempotent replays, and late-arriving facts. Passing a slowly changing dimensions scd type 2 sql interview requires mastering both dimensional trade-offs and exact SQL execution semantics.
Temporal modeling is a core pillar in any complete technical interview preparation guide for data roles. This guide compares SCD Type 1 vs. Type 2 (alongside Type 3 and Type 6), outlines the canonical schema contract, walks through window-function and MERGE SQL queries, debugs an overlapping-interval outage, and provides an interview rubric.
SCD Type 1 vs. Type 2 (and When Type 3 or Type 6 Fits)
Before writing DDL, interviewers expect you to match each attribute to the right SCD strategy. Versioning noisy columns like last_login_ip inflates storage and slows joins without analytical benefit.

In SCD Type 1, updates overwrite the existing row in place. History is discarded, so past facts reflect the entity's current state—ideal for typo corrections or non-historical metadata.
In SCD Type 2, each tracked change expires the active row by setting valid_to and is_current = FALSE, then inserts a new row with a fresh surrogate key and open validity window. Fact tables preserve exact point-in-time context so Finance sees the tier or territory that applied when each invoice posted.
Dimensional Strategy Comparison Matrix
When defending data modeling decisions in a sql interview, compare strategies across these criteria:
| SCD Strategy | Historical Preservation | Storage & Write Cost | Join Complexity | Best Production Use Case |
|---|---|---|---|---|
| Type 0 (Fixed) | Keeps initial value; rejects updates | Minimal (write-once) | Equality (=) join | Signup cohort, birth date, original acquisition channel |
| Type 1 (Overwrite) | None; history reflects current value | Minimal (1 row/entity) | Equality (=) join | Typo fixes, normalized phone/email, operational flags |
| Type 2 (Versioned) | Full audit trail across all changes | Moderate-high; grows with churn | Range (>= and <) or fact-stored sk | Subscription tiers, sales territories, product pricing |
| Type 3 (Prior Column) | Current + N prior values (prev_tier) | Low (fixed row width) | Equality (=) join | One-time territory re-orgs or before/after comparisons |
| Type 6 (Hybrid 1+2+3) | Type 2 history plus Type 1 current_tier | Moderate-high; updates old rows | Supports "as-was" and "as-is" slicing | Cohort reporting under both historical and current orgs |
Senior candidates also mention mini-dimensions (SCD Type 4): splitting rapidly changing attributes (like daily credit scores) into a separate dimension keeps the core dim_customers star schema lean. See how dimensional cores pair with denormalized marts in our dbt OBT vs. Kimball Star Schema data modeling interview guide.
Designing the Canonical SCD Type 2 Schema
A clean CREATE TABLE definition in a data warehouse interview signals production rigor across five invariants:
- Version Surrogate Key (
customer_sk): Uniquely identifies one version of a customer—never the naturalcustomer_id, which repeats across versions. - Natural Key (
customer_id): Groups all historical versions of the same upstream entity. - Tracked Columns &
attribute_hash: Hashing tracked columns (COALESCE-wrapped) suppresses phantom versions when upstream CDC emits unchanged payloads. - Half-Open Bounds (
valid_from,valid_to): Store[valid_from, valid_to)—inclusive start, exclusive end—using'9999-12-31 23:59:59'for open rows. - Active Flag (
is_current): Enables fastWHERE is_current = TRUEoperational lookups.
CREATE TABLE dim_customers_scd2 (
customer_sk VARCHAR(64) PRIMARY KEY,
customer_id BIGINT NOT NULL,
plan_tier VARCHAR(32) NOT NULL,
sales_region VARCHAR(32) NOT NULL,
attribute_hash VARCHAR(64) NOT NULL,
valid_from TIMESTAMP NOT NULL,
valid_to TIMESTAMP NOT NULL,
is_current BOOLEAN NOT NULL
);
CREATE UNIQUE INDEX ux_dim_customers_current
ON dim_customers_scd2 (customer_id)
WHERE is_current = TRUE;
That partial unique index (WHERE is_current = TRUE) enforces single-active-row integrity in PostgreSQL; in Snowflake or BigQuery, enforce the same rule with CI quality tests.
Writing SCD Type 2 in SQL: Window Functions vs. Idempotent MERGE
Interviewers test SCD Type 2 SQL in two ways: rebuilding history from an append-only event log and incrementally merging daily batches. Mastering both proves fluency in data architecture.

Pattern A: Rebuilding History with LAG() and LEAD()
Given raw_customer_events(customer_id, plan_tier, sales_region, event_ts, ingested_at) with duplicate snapshots, collapse consecutive unchanged rows ("gaps and islands") and build half-open intervals:
WITH deduped AS (
SELECT
customer_id, plan_tier, sales_region, event_ts,
ROW_NUMBER() OVER (
PARTITION BY customer_id, event_ts ORDER BY ingested_at DESC
) AS rn
FROM raw_customer_events
),
with_prev AS (
SELECT
customer_id, plan_tier, sales_region, event_ts,
LAG(plan_tier) OVER (PARTITION BY customer_id ORDER BY event_ts) AS prev_tier,
LAG(sales_region) OVER (PARTITION BY customer_id ORDER BY event_ts) AS prev_region
FROM deduped WHERE rn = 1
),
changes_only AS (
SELECT customer_id, plan_tier, sales_region, event_ts AS valid_from
FROM with_prev
WHERE prev_tier IS NULL
OR plan_tier IS DISTINCT FROM prev_tier
OR sales_region IS DISTINCT FROM prev_region
)
SELECT
MD5(CONCAT(customer_id, '|', valid_from)) AS customer_sk,
customer_id, plan_tier, sales_region, valid_from,
LEAD(valid_from, 1, TIMESTAMP '9999-12-31 23:59:59') OVER (
PARTITION BY customer_id ORDER BY valid_from
) AS valid_to,
LEAD(valid_from) OVER (PARTITION BY customer_id ORDER BY valid_from) IS NULL AS is_current
FROM changes_only;
Highlight IS DISTINCT FROM during live coding: standard != drops transitions to or from NULL because NULL != 'free' evaluates to UNKNOWN. This null-safe pattern recurs frequently in SQL interview questions for data engineers.
Pattern B: Incremental Updates with Atomic MERGE
For large warehouses, rebuilds on every run waste compute. Instead, expire changed active rows and insert new versions inside a transaction:
-- 1. Expire active rows whose tracked attribute_hash changed
MERGE INTO dim_customers_scd2 AS t
USING stg_customers_latest AS s
ON t.customer_id = s.customer_id AND t.is_current = TRUE
WHEN MATCHED AND t.attribute_hash <> s.attribute_hash
AND s.effective_ts > t.valid_from THEN
UPDATE SET t.valid_to = s.effective_ts, t.is_current = FALSE;
-- 2. Insert brand-new entities and newly opened versions
INSERT INTO dim_customers_scd2 (
customer_sk, customer_id, plan_tier, sales_region,
attribute_hash, valid_from, valid_to, is_current
)
SELECT
MD5(CONCAT(s.customer_id, '|', s.effective_ts)),
s.customer_id, s.plan_tier, s.sales_region,
s.attribute_hash, s.effective_ts, TIMESTAMP '9999-12-31 23:59:59', TRUE
FROM stg_customers_latest AS s
LEFT JOIN dim_customers_scd2 AS c
ON c.customer_id = s.customer_id AND c.is_current = TRUE
WHERE c.customer_id IS NULL;
Always wrap both statements in an atomic BEGIN ... COMMIT block—or use a single-statement MERGE with a UNION ALL staging split so expiration and insertion succeed or fail together. Discussing micro-partition rewrites versus Delta Lake MERGE links SQL mechanics to Snowflake vs. Databricks data architecture interviews and streaming vs. batch ETL with Kafka and Flink.
Point-in-Time Fact Joins & Why BETWEEN Double Counts
Next, interviewers ask how to join fct_invoices to dim_customers_scd2 without corrupting ARR when an invoice matches an exact tier-change timestamp:
-- ❌ BUGGY: Inclusive BETWEEN matches BOTH expired and new rows at boundary timestamps
SELECT d.plan_tier, SUM(f.amount_usd) AS arr_usd
FROM fct_invoices f
JOIN dim_customers_scd2 d
ON f.customer_id = d.customer_id
AND f.invoice_ts BETWEEN d.valid_from AND d.valid_to;
-- ✅ CORRECT: Half-open [valid_from, valid_to) guarantees at most one match
SELECT d.plan_tier, SUM(f.amount_usd) AS arr_usd
FROM fct_invoices f
JOIN dim_customers_scd2 d
ON f.customer_id = d.customer_id
AND f.invoice_ts >= d.valid_from
AND f.invoice_ts < d.valid_to;
For high-volume BI dashboards, range joins (>= and <) can force expensive scans. Resolve customer_sk once during the fct_invoices ETL load so BI queries perform fast equality joins (f.customer_sk = d.customer_sk). For deeper range-scan behavior in row stores, see PostgreSQL B-Tree vs. GIN indexing optimization.
Production Failure Scenario: Fixing Overlapping Intervals & Late Facts
Scenario: "An upstream Kafka topic replayed 48 hours of account events out of order. Today, Finance reports March revenue jumped 34%, and
COUNT(*)onfct_invoices JOIN dim_customers_scd2exceedsfct_invoicesrow count by 34%. Diagnose the dimension bug, handle facts arriving before a customer's first dimension version, and make backfills replay-safe."
1. Audit Intervals with LEAD()
WITH checked AS (
SELECT
customer_id, valid_from, valid_to,
LEAD(valid_from) OVER (
PARTITION BY customer_id ORDER BY valid_from, customer_sk
) AS next_valid_from
FROM dim_customers_scd2
)
SELECT customer_id, valid_from, valid_to, next_valid_from
FROM checked
WHERE next_valid_from < valid_to
OR next_valid_from > valid_to
OR valid_from >= valid_to;
Root Cause: Out-of-order replay events bypassed WHERE is_current = TRUE checks or inserted historical timestamps behind already-active rows, leaving overlapping [valid_from, valid_to) ranges and duplicate is_current = TRUE rows. Every invoice touching an overlap was counted twice.
2. Replay-Safe Fix & Early-Arriving Facts
- Key-Level Timeline Rebuild: For any
customer_idtouched in a backfill or replay window, recompute its complete timeline fromraw_customer_eventsusing Pattern A and atomically replace that customer's slice inside a transaction—applying the same replay discipline covered in idempotency in payment systems. - Inferred Members for Late Dimensions: If an invoice arrives at
10:00before the customer signup row lands at10:05, an inner range join drops revenue. Insert an inferred placeholder row (plan_tier = 'UNKNOWN',valid_from = '1900-01-01',valid_to = first_real_ts) and backfill attributes via Type 1 overwrite when the signup arrives. - CI Invariants: Fail pipeline runs if any
customer_idhas overlapping bounds, multipleis_current = TRUErows, orCOUNT(joined_facts) <> COUNT(fct_invoices). Review related pipeline safeguards in core data engineering interview questions.
SCD Type 2 Interview Scoring Rubric
| Evaluation Axis | Weak / Red-Flag Answer | Senior / Strong Hire Signal |
|---|---|---|
| Boundary Semantics | Uses BETWEEN and ignores exact timestamp collisions. | Enforces half-open [valid_from, valid_to) bounds and tests boundary equality. |
| Change Detection | Inserts duplicate versions on unchanged batches or uses !=. | Hashes tracked columns and applies null-safe IS DISTINCT FROM. |
| Join Performance | Runs range joins across billions of fact rows in live BI tools. | Resolves customer_sk at fact load time for equality joins in BI marts. |
| Out-of-Order Data | Assumes CDC arrives strictly in chronological order. | Uses key-scoped timeline rebuilds for replays and inferred members for late dimensions. |
| Quality Gates | Only tests NOT NULL on customer_id. | Enforces unique is_current = TRUE, LEAD() overlap checks, and fact row-count parity. |
Practice SCD SQL & Data Modeling Under Pressure
Writing LAG()/LEAD() queries without a timer is very different from diagnosing a live fan-out revenue incident while an interviewer probes your MERGE transaction boundaries.
- Test Your Recall in 60 Seconds: Play a rapid-fire round on the 60-Second Job Blitz to benchmark your SQL and data modeling instincts with zero login required.
- Practice Live with an AI Socratic Tutor: Paste a Data Engineer or Analytics Engineer job description into totop.app for tailored mock interviews that probe your SCD Type 2 schema, half-open joins, and backfill safety aloud.
- Explore Plans: Start with 10 free AI interview practice tests or unlock unlimited voice and text sessions on the totop.app pricing page.
Practice Staff Backend Engineer Questions Live with AI Mock Interviews
Turn any job description across Engineering, DevOps, Data, Marketing, Sales, Finance, or HR into a personalized test and live voice or text AI mock interview on totop.app, or test your speed right now in the 60-Second Staff Backend Engineer Blitz.
Play 60s Staff Backend Engineer Blitz (Free, No Login) | Start 14-Day Free Trial | Browse All Interview Guides