Slowly changing dimension type 2 in SQL and ClickHouse

SCD types 1, 2 and 6 in plain terms, SCD2 in SQL with valid_from and valid_to, point-in-time joins, and an append-only way to build it on ClickHouse without updates.

A slowly changing dimension type 2 (SCD2) keeps a new row for every version of an entity instead of overwriting the old one, and stamps each row with the time range it was true, so a fact can be joined to the attributes that applied when it happened. If a customer moved from the starter plan to pro in March, an SCD2 customer dimension holds both rows, and February revenue still reports under starter. The Kimball Group’s definition asks for at least three extra columns: a row effective date, a row expiration date, and a current row indicator. Most warehouses build that with a MERGE that closes the old row and inserts the new one. ClickHouse has no MERGE, and updates are expensive there, so the practical pattern is different: store each version once, append-only, and derive valid_to at read time. Every query below was run on ClickHouse 26.10, and the outputs shown are the real results.

What is a slowly changing dimension?

A dimension is the descriptive side of a star schema: customers, products, employees, stores. Its attributes change rarely and unpredictably, which is where “slowly changing” comes from. The question each SCD type answers is what happens to history when an attribute changes. Kimball’s numbering is the one everyone uses:

TypeWhat happens on a changeHistory keptTypical use
0Nothing; the original value is keptOriginal value onlySignup date, original channel
1The value is overwrittenNoneTypo fixes, email address
2A new row is added with a validity rangeFullPlan, region, sales owner, price tier
3A “previous value” column is addedOne prior valueA one-off reorganisation
6Type 2 rows plus a current-value column on every rowFull, plus currentReporting both “as was” and “as is”

Kimball describes type 6 as type 2 rows that also embed the current type 1 value of the same attribute, overwritten on every row of that entity, so a report can group by either the value in effect at the time or today’s value.

SCD type 1 vs type 2 vs type 6, on one example

Take customer 1, who signed up on the starter plan in Lithuania, upgraded to pro on 20 March, and moved to Germany on 1 June. Here is what each type stores:

TypeRows for customer 1
1pro, DE (one row; the history is gone)
2starter, LT from 10 Jan to 20 Mar; pro, LT from 20 Mar to 1 Jun; pro, DE from 1 Jun, current
6The same three type 2 rows, each with current_plan = pro and current_country = DE

With type 1, a February order for 49 reports as pro revenue from Germany, which never happened. With type 2, it reports as starter revenue from Lithuania. With type 6, you can show both on one chart: revenue by plan at the time of the order, split by the plan the customer is on today. That second view is what answers questions like “how much of today’s pro base started on starter?”

Most teams need type 1 for most attributes and type 2 for a handful. The semantic layer guide makes the same point: SCD2 matters for maybe two of your ten dimensions, so ship the rest first.

How do you build SCD type 2 in SQL?

The textbook SCD2 table has a surrogate key, the natural key, the tracked attributes, and three housekeeping columns:

ColumnMeaning
customer_skSurrogate key, one per version
customer_idNatural key from the source
valid_fromWhen this version became true (inclusive)
valid_toWhen the next version replaced it (exclusive)
is_current1 for the latest version

Two conventions save a lot of pain later:

  • Use half-open ranges. A row is valid where valid_from <= t AND t < valid_to. The next version’s valid_from equals this version’s valid_to, so there are no gaps, and a timestamp that falls exactly on a boundary matches exactly one row. With BETWEEN it matches two, and the fact is counted twice.
  • Give the current row a far-future valid_to such as 9999-12-31 rather than NULL. Range predicates then work without COALESCE, and is_current becomes a convenience column rather than a required one.

On Snowflake, BigQuery, Postgres 15 or SQL Server, the load is usually a MERGE: for every incoming row whose tracked attributes differ from the current version, update the current row to set valid_to and is_current = 0, then insert the new version. dbt snapshots automate exactly this. A snapshot compares the source with its history on every run, using either an updated_at column (the timestamp strategy) or a list of columns (the check strategy), and maintains dbt_valid_from and dbt_valid_to for you. Since dbt 1.9, hard_deletes controls whether a row deleted in the source is ignored, closed, or recorded as a new row with dbt_is_deleted, and dbt_valid_to_current replaces the default NULL on current rows with a far-future date.

You can also build the same table without an update step. If you keep one row per version with only valid_from, the window function lead() gives you valid_to:

SELECT
    customer_id, plan, country, valid_from,
    lead(valid_from, 1, TIMESTAMP '9999-12-31 00:00:00')
        OVER (PARTITION BY customer_id ORDER BY valid_from) AS valid_to
FROM customer_versions;

That one query is standard SQL, and it is the foundation of the ClickHouse approach below. One ClickHouse catch: there, TIMESTAMP '9999-12-31 00:00:00' is a plain DateTime, which silently caps at 2106-02-07, so the view below uses toDateTime64 for the default instead.

Point-in-time joins: attributes as of the event

A point-in-time join attaches to each fact the dimension version that was valid at the fact’s timestamp. With valid_from and valid_to in place, it is a range join on top of the key:

SELECT o.order_id, o.amount, d.plan, d.country
FROM orders AS o
LEFT JOIN customer_scd2 AS d
    ON  o.customer_id = d.customer_id
    AND o.ordered_at >= d.valid_from
    AND o.ordered_at <  d.valid_to;

The Kimball approach avoids the range join at query time: the fact table stores the surrogate key of the version that was current when the fact was loaded, and the join becomes a plain equality on customer_sk. That is fast, but it fixes the version at load time. If a dimension change arrives late, or you rebuild the dimension, every fact loaded in between points at the wrong version until you reload it. Joining on time is slower per query but always reflects the dimension as it stands now. On a column store with cheap scans, most teams join on time.

The ClickHouse way: append versions, derive valid_to

ClickHouse makes the textbook load awkward for two reasons. There is no MERGE statement, and an UPDATE that closes the old row is either a mutation, which rewrites data parts in the background, or a lightweight update with its own overhead. The ClickHouse delete and update guide covers those costs. SCD2 does not need any of it. Store each version exactly once, never touch it again, and compute valid_to when you read.

1. A versions table keyed on entity and time

CREATE TABLE customer_versions
(
    customer_id UInt64,
    plan        LowCardinality(String),
    country     LowCardinality(String),
    valid_from  DateTime64(3, 'UTC')
)
ENGINE = ReplacingMergeTree
ORDER BY (customer_id, valid_from);

INSERT INTO customer_versions VALUES
    (1, 'starter', 'LT', '2026-01-10 09:00:00'),
    (1, 'pro',     'LT', '2026-03-20 12:00:00'),
    (1, 'pro',     'DE', '2026-06-01 08:00:00'),
    (2, 'pro',     'FR', '2026-02-01 00:00:00');

ReplacingMergeTree with (customer_id, valid_from) as the sort key makes loads idempotent: if a retry inserts the same version twice, the copies collapse to one row on merge, and FINAL hides them before that. The sort key also puts each customer’s versions next to each other in time order, which is what both the window function and the ASOF join below want. The ReplacingMergeTree guide explains how FINAL picks the surviving row.

2. A view that adds valid_to and is_current

CREATE VIEW customer_scd2 AS
SELECT
    customer_id, plan, country, valid_from,
    lead(valid_from, 1, toDateTime64('9999-12-31 00:00:00', 3, 'UTC'))
        OVER (PARTITION BY customer_id ORDER BY valid_from) AS valid_to,
    valid_to = toDateTime64('9999-12-31 00:00:00', 3, 'UTC') AS is_current
FROM customer_versions FINAL;
customer_id  plan     country  valid_from           valid_to             is_current
1            starter  LT       2026-01-10 09:00:00  2026-03-20 12:00:00  0
1            pro      LT       2026-03-20 12:00:00  2026-06-01 08:00:00  0
1            pro      DE       2026-06-01 08:00:00  9999-12-31 00:00:00  1
2            pro      FR       2026-02-01 00:00:00  9999-12-31 00:00:00  1

Use lead, not leadInFrame, unless you also set the frame. The window functions reference notes that leadInFrame respects the window frame, and with the default frame it cannot see the next row; to make it behave like lead you need ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING. DateTime64 at precision 3 accepts 9999-12-31, but at precision 6 the same literal overflowed in our test, and a plain DateTime stops in 2106, so pick the sentinel to match the type.

The payoff shows up when a change arrives late. Suppose you learn today that customer 1 was briefly on enterprise from 1 May. With stored valid_to values you would have to find and update the pro row that now ends earlier. Here you insert one row, and the view recomputes:

INSERT INTO customer_versions VALUES (1, 'enterprise', 'LT', '2026-05-01 00:00:00');
customer_id  plan        country  valid_from           valid_to
1            starter     LT       2026-01-10 09:00:00  2026-03-20 12:00:00
1            pro         LT       2026-03-20 12:00:00  2026-05-01 00:00:00
1            enterprise  LT       2026-05-01 00:00:00  2026-06-01 08:00:00
1            pro         DE       2026-06-01 08:00:00  9999-12-31 00:00:00

3. Load only the rows that changed

Your source usually gives you the current state of each customer, from a full extract or an incremental pipeline. To turn that into versions, compare each source row with the latest stored version and insert only the differences:

INSERT INTO customer_versions
SELECT s.customer_id, s.plan, s.country, s.updated_at AS valid_from
FROM customers_src AS s
LEFT JOIN
(
    SELECT customer_id,
           argMax(plan, valid_from)    AS plan,
           argMax(country, valid_from) AS country
    FROM customer_versions
    GROUP BY customer_id
) AS cur ON s.customer_id = cur.customer_id
WHERE cur.customer_id IS NULL
   OR (s.plan, s.country) != (cur.plan, cur.country)
SETTINGS join_use_nulls = 1;

This is the check strategy in SQL. New customers (cur.customer_id IS NULL) and customers whose tracked attributes differ get a new version; everyone else is skipped. Run it again with the same source and it inserts zero rows. join_use_nulls = 1 matters: without it, ClickHouse fills unmatched columns of a LEFT JOIN with type defaults, so a new customer would show cur.customer_id = 0 rather than NULL. List only the attributes you want history for in the comparison. Changes to anything else, such as an email address, belong in a separate type 1 table or a plain current-state view.

For deletes, add an is_deleted UInt8 DEFAULT 0 column and insert a version with is_deleted = 1 when a customer disappears from the source. The previous version then closes at the delete time, and reports filter on NOT is_deleted where needed.

4. Join facts with ASOF JOIN

ClickHouse has a join made for this problem. ASOF JOIN matches each left row to the closest right row that satisfies one inequality, so it needs only valid_from:

SELECT o.order_id, o.ordered_at, o.amount, v.plan, v.country
FROM orders AS o
ASOF LEFT JOIN customer_versions AS v
    ON o.customer_id = v.customer_id
   AND o.ordered_at >= v.valid_from
SETTINGS join_use_nulls = 1;
order_id  ordered_at           amount  plan     country
101       2026-01-05 10:00:00  20      NULL     NULL
102       2026-02-14 10:00:00  49      starter  LT
103       2026-03-20 12:00:00  199     pro      LT
104       2026-07-02 10:00:00  199     pro      DE
105       2026-04-01 10:00:00  199     pro      FR

Order 103 lands exactly on the upgrade timestamp and matches pro, the version that starts there, which is the half-open behaviour you want. Order 101 predates the first version, so it gets NULL. Without join_use_nulls = 1 it would get an empty string, which a GROUP BY plan would quietly report as a plan with no name. Per the JOIN reference, the ASOF condition supports >, >=, < and <=, only the hash and full_sorting_merge algorithms support ASOF, and with hash you need at least one equality condition, which the customer_id match provides. Join the versions table here, not the view; with ASOF the lead() is unnecessary work. Read it with FINAL if duplicate versions are possible. The plain range join from the previous section also runs on ClickHouse 26.10 against the view, and returns the same rows. For more on how ClickHouse executes joins and how to pick the algorithm, see the join performance guide.

5. Or look versions up from a range_hashed dictionary

For a dimension that fits in memory and is joined from many large fact queries, a range_hashed dictionary turns the join into a per-row lookup by key and timestamp:

CREATE DICTIONARY customer_hist
(
    customer_id UInt64,
    plan        String,
    country     String,
    valid_from  DateTime64(3, 'UTC'),
    valid_to    DateTime64(3, 'UTC')
)
PRIMARY KEY customer_id
SOURCE(CLICKHOUSE(TABLE 'customer_scd2'))
LIFETIME(MIN 300 MAX 600)
LAYOUT(RANGE_HASHED(range_lookup_strategy 'max'))
RANGE(MIN valid_from MAX valid_to);

SELECT order_id,
       dictGet('customer_hist', ('plan', 'country'), customer_id, ordered_at) AS attrs
FROM orders;

Watch the boundary. Dictionary ranges include both ends, so a timestamp equal to one version’s valid_to and the next version’s valid_from matches both. With the default range_lookup_strategy 'min', ClickHouse returns the range with the smallest valid_from, which is the old version: in our test, a lookup at exactly 20 March 12:00 returned starter. Setting 'max' returns the newer version and restores half-open behaviour. When no range matches, dictGet returns the type’s default and dictGetOrNull returns NULL. The dictionary also reloads on its LIFETIME schedule, so a fresh version can take up to that long to show up.

6. Materialize the view when it gets big

The view re-runs FINAL and a window function on every query. For a dimension with millions of versions that is wasted work, so store the result and refresh it on a schedule. A refreshable materialized view replaces the target table’s contents atomically on each run:

CREATE MATERIALIZED VIEW customer_scd2_refresh
REFRESH EVERY 1 HOUR TO customer_scd2_table AS
SELECT * FROM customer_scd2;

Non-append refreshable views need an Atomic or Replicated database. In clickhouse-local, whose default database uses a different engine, the statement fails until you create one.

SCD type 6 without overwriting rows

Classic type 6 rewrites the current-value column on every historical row whenever the entity changes. That is an update storm on ClickHouse, and unnecessary, because the current value is one window function away:

SELECT customer_id, plan, valid_from, valid_to,
       argMax(plan, valid_from) OVER (PARTITION BY customer_id) AS current_plan
FROM customer_scd2;

Join facts to that with ASOF, and one query reports both views. On our sample data, after customer 2 moved to enterprise in October:

plan_at_order  current_plan  revenue
pro            enterprise    199
pro            pro           398
starter        pro           49
NULL           NULL          20

The 49 of starter revenue now belongs to a pro customer, and the 199 of pro revenue belongs to an enterprise customer. Type 1 reporting would have shown neither.

Common SCD2 mistakes

  • Tracking columns that change often. Every change is a new row. Putting last_login_at or a balance in the comparison turns the dimension into an event log. Keep fast-changing values in a fact table, or in a separate small dimension.
  • Using load time as valid_from. If you stamp versions with now() at load time, history moves whenever a load is late or replayed. Use the source’s own change timestamp, such as updated_at or a log position from CDC. The incremental models guide covers the same lateness problem for facts.
  • Two versions with the same valid_from. With the sort key above, ReplacingMergeTree keeps only one of them, and a tie in argMax picks an arbitrary one. Use a timestamp precise enough to separate real changes.
  • Inclusive ranges on both sides. BETWEEN valid_from AND valid_to double-counts boundary facts. Use >= and <, or range_lookup_strategy 'max' in a dictionary.
  • Ignoring facts older than the first version. If the dimension starts the day you began tracking, earlier facts match nothing. Backfill a first version from the source’s creation date, or report those rows as unknown explicitly.

Where Goni fits

Whatever you build SCD2 with, it is a modelling job: a versions table, a change-detection load, a view or table with valid_to, and tests that catch overlapping ranges. Goni is one option for running that on ClickHouse. Full disclosure: this is our product. Its dbt-like YAML semantic layer lets you write models like the ones above as SQL, materialized as a view, a table or incrementally, with unique and not_null tests and column-level lineage, and its pipelines land source tables into a ClickHouse warehouse that also serves the SQL IDE, dashboards and AI Q&A grounded in your defined metrics. The honest drawbacks: ClickHouse is the only warehouse Goni queries, and it is younger than dbt, which has snapshots built in, so SCD2 in Goni is a model you write yourself. You can try it with the 14-day free trial.

FAQ

What is the difference between SCD type 1 and type 2?

Type 1 overwrites the old value, so the dimension always shows the current state and history is lost. Type 2 adds a new row for each change, with a validity range, so facts can be reported with the attributes that applied when they happened. Use type 1 for corrections and type 2 for attributes whose history affects analysis.

What columns does an SCD type 2 table need?

At minimum, the natural key, the tracked attributes, a valid_from timestamp and a valid_to timestamp, plus an is_current flag for convenience. Kimball adds a surrogate key per version, used as the fact table’s foreign key. Make ranges half-open and give the current row a far-future valid_to such as 9999-12-31.

How do you implement SCD type 2 in ClickHouse?

Store one row per version in a ReplacingMergeTree ordered by key and valid_from, inserting only rows whose tracked attributes changed. Derive valid_to with lead() in a view, join facts with ASOF JOIN on key and valid_from, and materialize the view on a schedule once it gets large. No updates or mutations are needed.

Does dbt support SCD type 2?

Yes. dbt snapshots implement type 2: they detect changes with the timestamp or check strategy and maintain dbt_valid_from and dbt_valid_to columns. Since dbt 1.9, snapshots are configured in YAML and can record hard deletes as new rows. The dbt-clickhouse adapter lists snapshots among its supported features.

What is SCD type 6?

Type 6 builds on type 2: it keeps type 2 history and stores the entity’s current type 1 value as a column on every row, overwritten whenever it changes. That lets one query group facts by both the value at the time and today’s value. On ClickHouse, compute the current value with a window function rather than rewriting old rows.