# Slowly changing dimensions done right: SCD Type 2, surrogate keys and point-in-time fact loads

A customer moves from SMB to Enterprise. Should last spring's revenue move with them? This guide builds a Type 2 customer dimension in runnable SQL, loads facts against the version valid at order time, answers both questions, and maps it to Spark 4.3's new SCD Type 2 Auto CDC.

Facts record what happened: an order, a payment, a shipment. Dimensions describe the things involved: the customer, the product, the store. Facts are written once and rarely change. Dimension attributes change all the time. A customer is reclassified, a product moves category, a store changes region. How a warehouse handles those changes decides whether last year's report still shows last year's truth.

This article teaches the standard answer, the Type 2 slowly changing dimension (SCD), from the ground up. We build a customer dimension with surrogate keys and validity ranges, load a fact table so each order points at the customer version that was true when the order happened, and then answer both "revenue by segment at the time of sale" and "revenue by current segment". The SQL runs as written in DuckDB 2.0.1. Finally we map the same ideas onto the SCD Type 2 support that Apache Spark 4.3 added to its Declarative Pipelines.

## What happened

### Spark 4.3.0 adds SCD Type 2 to Auto CDC (30 October 2026)

Apache Spark 4.3.0, released on 30 October 2026, adds history-preserving SCD Type 2 to Auto CDC in Spark Declarative Pipelines, available through Python, SQL and Spark Connect. According to the Spark documentation, a Type 2 target gains two columns, `__START_AT` and `__END_AT`, holding the sequence values at which each version became and stopped being current, with `__END_AT` null for the current version.

### Spark 4.3.0 adds a SQL ASOF JOIN (30 October 2026)

The same release adds SQL `ASOF JOIN ... MATCH_CONDITION` syntax with a sort-merge execution, for point-in-time matching of events to the information available at that time. The release notes say it is enabled with `spark.sql.join.asofJoin.enabled`, which is off by default.

## Facts first: grain and types

Before dimensions, be clear about facts. A fact table's **grain** is what one row means, such as "one order line". Kimball's dimensional modelling distinguishes three main fact table types:

| Fact table type | One row per | Example | How it changes |
|---|---|---|---|
| Transaction | Event | One order line | Insert only |
| Periodic snapshot | Entity per period | Account balance per day | One new row per period |
| Accumulating snapshot | Process instance | One order moving through placed, paid, shipped, delivered | Row updated as milestones happen |

Measures should be true at the stated grain. Additive measures (amount, quantity) can be summed across every dimension. Semi-additive measures (balances) can be summed across accounts but not across time. Non-additive measures (ratios, unit prices) must be recomputed from their parts.

## Dimension change types

When an attribute changes, there are a few classic responses:

| Type | Behaviour | Example use | History |
|---|---|---|---|
| Type 0 | Never change the value | Original signup date | Fixed |
| Type 1 | Overwrite | Fixing a typo in a name | Lost |
| Type 2 | Add a new row with validity dates | Segment, region, price list | Full |
| Type 3 | Keep the previous value in an extra column | Old and new sales territory during a reorganisation | One step back |

Type 2 is the workhorse because it preserves the truth at each point in time. The analogy is a passport: when you change your address, you do not erase the old stamps. You get a new page, and each stamp keeps the address you had when you travelled.

## Building a Type 2 dimension

### The table and the surrogate key

```sql
CREATE SEQUENCE customer_sk START 1;
CREATE TABLE dim_customer (
  customer_sk  BIGINT DEFAULT nextval('customer_sk'),  -- surrogate key, one per version
  customer_id  VARCHAR,                                -- business (natural) key
  segment      VARCHAR,
  city         VARCHAR,
  valid_from   TIMESTAMP,
  valid_to     TIMESTAMP,
  is_current   BOOLEAN);
```

The **surrogate key** is the heart of Type 2. The business key `customer_id` identifies the customer; the surrogate key identifies one version of that customer. Facts store the surrogate key, so each fact is permanently tied to the version that was true when it happened.

We use a half-open interval: a version is valid from `valid_from` (inclusive) to `valid_to` (exclusive). Current versions get a far-future `valid_to` of 9999-12-31, which keeps range joins simple.

Initial load, 1 January 2026:

| customer_sk | customer_id | segment | city | valid_from | valid_to | is_current |
|---|---|---|---|---|---|---|
| 1 | C1 | SMB | Izmir | 2026-01-01 | 9999-12-31 | true |
| 2 | C2 | Consumer | Berlin | 2026-01-01 | 9999-12-31 | true |

### Applying a change batch

On 1 June 2026 a staging table brings three records: C1 is now `Enterprise`, C2 is unchanged, C3 is new.

**Step 1: close versions whose tracked attributes changed.**

```sql
UPDATE dim_customer AS d
SET valid_to = s.changed_at, is_current = false
FROM stg_customer s
WHERE d.customer_id = s.customer_id
  AND d.is_current
  AND (d.segment IS DISTINCT FROM s.segment OR d.city IS DISTINCT FROM s.city);
```

`IS DISTINCT FROM` treats two nulls as equal, so a null that stays null does not create a fake new version.

**Step 2: insert new versions for changed and new customers.**

```sql
INSERT INTO dim_customer (customer_id, segment, city, valid_from, valid_to, is_current)
SELECT s.customer_id, s.segment, s.city, s.changed_at, TIMESTAMP '9999-12-31', true
FROM stg_customer s
LEFT JOIN dim_customer d ON d.customer_id = s.customer_id AND d.is_current
WHERE d.customer_id IS NULL;
```

After step 1, C1 has no current row, so it qualifies. C2 still has its current row and is skipped. C3 has no row at all and is inserted. The dimension now holds four rows:

| customer_sk | customer_id | segment | valid_from | valid_to | is_current |
|---|---|---|---|---|---|
| 1 | C1 | SMB | 2026-01-01 | 2026-06-01 | false |
| 3 | C1 | Enterprise | 2026-06-01 | 9999-12-31 | true |
| 2 | C2 | Consumer | 2026-01-01 | 9999-12-31 | true |
| 4 | C3 | SMB | 2026-06-01 | 9999-12-31 | true |

Running the same batch again changes nothing: step 1 finds no differences and step 2 finds current rows for everyone. That idempotency matters when jobs retry.

### Choosing which columns create versions

Not every attribute deserves history. An email correction should overwrite (Type 1); a segment change should version (Type 2). Mixing the two in one dimension is common: compare only the Type 2 columns in step 1, and update Type 1 columns on all versions of the key in a separate statement. Spark's Auto CDC exposes the same choice with `track_history_column_list` or `TRACK HISTORY ON`.

## Loading facts against the right version

Four orders arrive:

| order_id | customer_id | order_ts | amount |
|---|---|---|---|
| 1 | C1 | 2026-03-15 10:00 | 100 |
| 2 | C1 | 2026-07-02 09:00 | 250 |
| 3 | C2 | 2026-07-03 12:00 | 40 |
| 4 | C3 | 2026-08-01 08:00 | 75 |

The fact load looks up the surrogate key of the version valid at order time:

```sql
CREATE TABLE fact_orders AS
SELECT o.order_id, d.customer_sk, o.order_ts, o.amount
FROM stg_orders o
JOIN dim_customer d
  ON d.customer_id = o.customer_id
 AND o.order_ts >= d.valid_from
 AND o.order_ts <  d.valid_to;
```

Order 1 (March) gets `customer_sk` 1, the SMB version. Order 2 (July) gets 3, the Enterprise version. Orders 3 and 4 get 2 and 4.

### An ASOF join does the same thing

A range join needs both bounds. An ASOF join needs only the start: for each order it picks the latest dimension version that began at or before the order time.

```sql
SELECT o.order_id, d.customer_sk, d.segment
FROM stg_orders o
ASOF JOIN dim_customer d
  ON o.customer_id = d.customer_id
 AND o.order_ts >= d.valid_from;
```

In DuckDB this returns the same keys: 1 (SMB), 3 (Enterprise), 2 (Consumer), 4 (SMB). ASOF joins are also the natural tool for matching events to prices, exchange rates or sensor calibrations that were in force at the time, and Spark 4.3 now offers them in SQL behind a configuration flag.

## Two questions, two joins

With facts tied to versions, both business questions are easy.

**Revenue by segment at the time of sale:** join facts to the version they point at.

```sql
SELECT d.segment, sum(f.amount) AS revenue_at_time_of_sale
FROM fact_orders f JOIN dim_customer d USING (customer_sk)
GROUP BY ALL ORDER BY ALL;
```

Result: Consumer 40, Enterprise 250, SMB 175. C1's March order stays with SMB.

**Revenue by current segment:** hop from the fact's version to the current version of the same business key.

```sql
SELECT cur.segment, sum(f.amount) AS revenue_by_current_segment
FROM fact_orders f
JOIN dim_customer d   USING (customer_sk)
JOIN dim_customer cur ON cur.customer_id = d.customer_id AND cur.is_current
GROUP BY ALL ORDER BY ALL;
```

Result: Consumer 40, Enterprise 350, SMB 75. C1's March order now counts as Enterprise.

Neither answer is wrong. They answer different questions, and a Type 2 dimension lets you ask both without rebuilding anything.

## The same pattern in Spark 4.3 Auto CDC

Spark Declarative Pipelines can maintain a Type 2 table from a change feed:

```sql
CREATE STREAMING TABLE customers
FLOW AUTO CDC
FROM STREAM(cdc_events)
KEYS (id)
APPLY AS DELETE WHEN op = 'DELETE'
SEQUENCE BY version
COLUMNS * EXCEPT (op)
STORED AS SCD TYPE 2;
```

The documentation spells out the behaviour. The first event for a key opens a version; a later event that changes a tracked column closes the current version at its sequence value and opens a new one; a delete closes the current version without opening a new one; a re-delivered event adds no version; and a late event is placed in history at the position its sequence value gives it. In the documented example, versions at sequence values 10 and 30 exist, and late events at 20 and 5 split the first version at 20 and add an earlier version from 5 to 10.

| Concept | Hand-written SQL above | Spark Auto CDC Type 2 |
|---|---|---|
| Business key | `customer_id` | `KEYS (id)` |
| Ordering | `changed_at` | `SEQUENCE BY version` (any orderable, non-null expression) |
| Validity range | `valid_from`, `valid_to` | `__START_AT`, `__END_AT` |
| Current version | `is_current = true` | `__END_AT IS NULL` |
| Late events | Needs extra logic | Inserted at their sequence position |
| Target requirement | Any table supporting `UPDATE` | A streaming table whose format supports row-level operations (MERGE) |

Note one design difference: Auto CDC does not generate a surrogate key column. If your fact tables need one, derive it from the business key and `__START_AT`, or join facts by business key and time range.

## Conformed dimensions and late arrivals

Two more practices make dimensions work across a warehouse.

**Conformed dimensions** are shared by several fact tables with the same keys and attribute meanings. If orders and support tickets both use the same `dim_customer`, a report can compare them by segment without reconciliation. Conformance is an organisational agreement as much as a table.

**Late-arriving dimensions** happen when a fact arrives before its customer record. Rather than dropping the fact, point it at a placeholder member (often key -1, "Unknown") or insert an inferred member with only the business key, and update it when the full record arrives. Never let a missing dimension silently drop revenue.

## What it means in practice

Type 2 dimensions are what make historical reports stable. Without them, a reclassification rewrites history: last year's SMB revenue shrinks because some customers became Enterprise. With them, the warehouse can answer both "as it was" and "as it is" honestly. The cost is modest: a surrogate key, two dates, a flag and a two-step load.

The same pattern appears across tools. [dbt](/tools/dbt) snapshots build Type 2 tables from source tables. [Change data capture](/tools/change-data-capture) feeds supply the ordered events, and Spark's Auto CDC now applies them as Type 2 on formats such as [Apache Iceberg](/tools/apache-iceberg) and [Delta Lake](/tools/delta-lake) that support row-level operations. Dimensions usually live in the [gold layer](/tools/gold-layer), and [DuckDB](/tools/duckdb) is a handy place to prototype the SQL. For the engine side, see [Apache Spark](/tools/apache-spark) and the [lakehouse topic page](/topics/big-data/lakehouse).

## What to do now

1. **State every fact table's grain.** Write one sentence per table and check each measure is true at that grain.
2. **Classify attributes by change type.** Mark each dimension column as Type 0, 1, 2 or 3 before writing load code.
3. **Add surrogate keys to Type 2 dimensions.** Store them in facts so each fact points at one version.
4. **Use half-open validity ranges.** Use `valid_from` inclusive and `valid_to` exclusive with a far-future end date for current rows.
5. **Compare with `IS DISTINCT FROM`.** Avoid creating versions when nulls stay null.
6. **Test idempotency.** Apply the same change batch twice and confirm the dimension does not change the second time.
7. **Handle late facts with unknown or inferred members.** Never drop facts because a dimension row is missing.
8. **Try Auto CDC Type 2 on a copy.** If you run Spark 4.3, compare its `__START_AT` and `__END_AT` output with your current SCD logic on the same feed.

## Risks and open questions

**Wrong timestamps create wrong history.** If `changed_at` is the load time instead of the business change time, facts attach to the wrong versions.

**Version explosion.** Tracking history on noisy columns, such as last login time, creates a new version every day; track only attributes that matter for analysis.

**Overlapping or gapped ranges.** Bugs in close-and-insert logic can leave two current rows or a gap; add checks that each key has exactly one current version and no overlaps.

**Configuration flags gate new syntax.** Spark 4.3's SQL ASOF JOIN is off by default, so queries portable across clusters need the flag set consistently.

**Watch next:** how teams combine Spark's Auto CDC Type 2 tables with surrogate-keyed fact tables, and whether ASOF joins become the default way to load facts against versioned dimensions.

## Frequently asked questions

### What is a slowly changing dimension Type 2?

It is a dimension that keeps every version of an entity as a separate row with a validity range and usually a current flag. Facts point at the version that was true when they happened, so history stays accurate.

### Why use a surrogate key instead of the business key?

The business key identifies the entity, but a Type 2 dimension has several rows per entity. A surrogate key identifies one version, so facts can reference exactly the version they belong to.

### How do I report by the current attribute value instead?

Join the fact to its version, then join from that version's business key to the current row of the same key. This reassigns all history to today's attribute values.

### What is an ASOF join?

It matches each row to the most recent row in another table whose time is at or before it, for example the dimension version valid at order time. DuckDB supports it, and Spark 4.3 adds SQL ASOF JOIN behind a configuration flag.

### Does Spark Auto CDC create surrogate keys?

No. Its Type 2 output adds `__START_AT` and `__END_AT` columns based on the sequencing expression. If you need a surrogate key, derive one from the business key and the start value.

## Summary

Facts record events at a declared grain, while dimensions describe the entities involved and change over time. A Type 2 dimension keeps every version with a surrogate key, a half-open validity range and a current flag, built with a two-step close-and-insert load that is safe to rerun. Facts loaded with a range or ASOF join point at the version valid at the time, so our example could report C1's March order as SMB revenue at the time of sale and as Enterprise revenue by current segment. Spark 4.3.0, released on 30 October 2026, brings the same pattern to Declarative Pipelines with SCD Type 2 Auto CDC and adds a SQL ASOF JOIN.

## Sources

- [Apache Spark: Spark Release 4.3.0](https://spark.apache.org/releases/spark-release-4-3-0.html)
- [GitHub: Spark Release 4.3.0 notes source](https://github.com/apache/spark-website/blob/asf-site/releases/_posts/2026-10-30-spark-release-4-3-0.md)
- [GitHub: Spark Declarative Pipelines programming guide, Auto CDC](https://github.com/apache/spark/blob/master/docs/declarative-pipelines-programming-guide.md)
- [Kimball Group: Dimensional modeling techniques](https://www.kimballgroup.com/data-warehouse-business-intelligence-resources/kimball-techniques/dimensional-modeling-techniques/)
- [GitHub: DuckDB docs, ASOF join guide](https://github.com/duckdb/duckdb-web/blob/main/docs/2.0/guides/sql_features/asof_join.md)
- [DuckDB: Announcing DuckDB 2.0.1 LTS](https://duckdb.org/2026/11/20/announcing-duckdb-201.html)
