> ## Documentation Index
> Fetch the complete documentation index at: https://clickhouse.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# How to implement slowly changing dimensions (SCD type 2) in ClickHouse

> Keep every version of a dimension row in an append-only table, detect changes at insert time with a materialized view, and query validity intervals with a window function or ASOF JOIN.

A [type 2 slowly changing dimension](https://en.wikipedia.org/wiki/Slowly_changing_dimension#Type_2:_add_new_row) keeps every version of a dimension row instead of overwriting it. In ClickHouse, store the versions in an append-only table and let a materialized view decide at insert time whether an incoming row differs from the current version. Validity intervals do not have to be stored or updated: compute them with a window function, or look up the version that was valid at a given time with `ASOF JOIN`.

If you load data with dbt or Fivetran, they can maintain such a table for you: see [dbt snapshots](https://clickhouse.com/docs/integrations/connectors/data-ingestion/etl-tools/dbt/materializations.md#snapshot) and [Fivetran history mode](https://clickhouse.com/docs/integrations/connectors/data-ingestion/etl-tools/fivetran/reference.md#history-mode).

## Tables and materialized view

```sql theme={null}
CREATE TABLE customers_input
(
    customer_id UInt32,
    name String,
    city String,
    updated_at DateTime('UTC')
)
ENGINE = Null;

CREATE TABLE customers_history
(
    customer_id UInt32,
    name String,
    city String,
    version UInt32,
    valid_from DateTime('UTC'),
    row_hash UInt64 MATERIALIZED cityHash64(name, city)
)
ENGINE = ReplacingMergeTree
ORDER BY (customer_id, version);

CREATE MATERIALIZED VIEW customers_history_mv TO customers_history AS
SELECT
    i.customer_id AS customer_id,
    i.name AS name,
    i.city AS city,
    c.last_version + 1 AS version,
    i.updated_at AS valid_from
FROM customers_input AS i
LEFT JOIN
(
    SELECT
        customer_id,
        max(version) AS last_version,
        argMax(row_hash, version) AS last_hash
    FROM customers_history
    WHERE customer_id IN (SELECT customer_id FROM customers_input)
    GROUP BY customer_id
) AS c ON i.customer_id = c.customer_id
WHERE c.last_version = 0 OR c.last_hash != cityHash64(i.name, i.city)
SETTINGS join_use_nulls = 0;
```

How it works:

* Every load inserts into `customers_input`. It uses the [`Null`](https://clickhouse.com/docs/reference/engines/table-engines/special/null) engine, so the rows are not stored there: they only pass through the materialized view.
* `customers_history` holds one row per version of a customer. `row_hash` is a hash of the attributes whose changes you want to track.
* For every inserted block, the view looks up the latest version of each incoming key. The `LEFT JOIN` returns default values for a key without history, so `last_version = 0` means a new key. The view keeps the rows of new keys and the rows whose hash differs from the hash of the latest version, and gives them the number `last_version + 1`. Unchanged rows are discarded.
* Inside a materialized view, the source table stands for the inserted block, [also in subqueries](https://clickhouse.com/docs/concepts/features/materialized-views/incremental-materialized-view.md#using-source-table-in-filters-and-joins-in-materialized-views). The condition `customer_id IN (SELECT customer_id FROM customers_input)` therefore limits the lookup to the keys of the block, and the primary key of `customers_history` is used to read only their history instead of the whole table.
* `SETTINGS join_use_nulls = 0` fixes the behavior of the `LEFT JOIN` that the view relies on. Without it, an insert from a session with [`join_use_nulls = 1`](https://clickhouse.com/docs/reference/settings/session-settings/join#join_use_nulls) silently skips new keys, because `last_version` is then `NULL` for them.
* [`ReplacingMergeTree`](https://clickhouse.com/docs/reference/engines/table-engines/mergetree-family/replacingmergetree) with the sorting key `(customer_id, version)` leaves at most one row per version of a key after merges.

`valid_from` is taken from the change time that the source provides. If the source has none, use `now() AS valid_from` in the view to record the load time.

## Load data

The first load creates version 1 of each customer:

```sql theme={null}
INSERT INTO customers_input VALUES
    (1, 'Alice', 'Berlin', '2026-01-01 00:00:00'),
    (2, 'Bob', 'Paris', '2026-01-01 00:00:00');

SELECT * FROM customers_history ORDER BY customer_id, version;
```

```text theme={null}
   ┌─customer_id─┬─name──┬─city───┬─version─┬──────────valid_from─┐
1. │           1 │ Alice │ Berlin │       1 │ 2026-01-01 00:00:00 │
2. │           2 │ Bob   │ Paris  │       1 │ 2026-01-01 00:00:00 │
   └─────────────┴───────┴────────┴─────────┴─────────────────────┘
```

Loading the same attributes again adds nothing:

```sql theme={null}
INSERT INTO customers_input VALUES
    (1, 'Alice', 'Berlin', '2026-02-01 00:00:00'),
    (2, 'Bob', 'Paris', '2026-02-01 00:00:00');

SELECT count() FROM customers_history;
```

```text theme={null}
   ┌─count()─┐
1. │       2 │
   └─────────┘
```

A load with one changed customer, one unchanged customer and one new customer adds two rows:

```sql theme={null}
INSERT INTO customers_input VALUES
    (1, 'Alice', 'Madrid', '2026-03-01 00:00:00'),
    (2, 'Bob', 'Paris', '2026-03-01 00:00:00'),
    (3, 'Carol', 'Rome', '2026-03-01 00:00:00');

SELECT * FROM customers_history ORDER BY customer_id, version;
```

```text theme={null}
   ┌─customer_id─┬─name──┬─city───┬─version─┬──────────valid_from─┐
1. │           1 │ Alice │ Berlin │       1 │ 2026-01-01 00:00:00 │
2. │           1 │ Alice │ Madrid │       2 │ 2026-03-01 00:00:00 │
3. │           2 │ Bob   │ Paris  │       1 │ 2026-01-01 00:00:00 │
4. │           3 │ Carol │ Rome   │       1 │ 2026-03-01 00:00:00 │
   └─────────────┴───────┴────────┴─────────┴─────────────────────┘
```

A value that returns to an earlier state is a new version, because the view compares with the latest version only:

```sql theme={null}
INSERT INTO customers_input VALUES
    (1, 'Alice', 'Berlin', '2026-04-01 00:00:00');

SELECT * FROM customers_history ORDER BY customer_id, version;
```

```text theme={null}
   ┌─customer_id─┬─name──┬─city───┬─version─┬──────────valid_from─┐
1. │           1 │ Alice │ Berlin │       1 │ 2026-01-01 00:00:00 │
2. │           1 │ Alice │ Madrid │       2 │ 2026-03-01 00:00:00 │
3. │           1 │ Alice │ Berlin │       3 │ 2026-04-01 00:00:00 │
4. │           2 │ Bob   │ Paris  │       1 │ 2026-01-01 00:00:00 │
5. │           3 │ Carol │ Rome   │       1 │ 2026-03-01 00:00:00 │
   └─────────────┴───────┴────────┴─────────┴─────────────────────┘
```

## Query the history

The current state is the latest version of each key:

```sql theme={null}
SELECT customer_id, name, city, version, valid_from
FROM customers_history
ORDER BY customer_id, version DESC
LIMIT 1 BY customer_id;
```

```text theme={null}
   ┌─customer_id─┬─name──┬─city───┬─version─┬──────────valid_from─┐
1. │           1 │ Alice │ Berlin │       3 │ 2026-04-01 00:00:00 │
2. │           2 │ Bob   │ Paris  │       1 │ 2026-01-01 00:00:00 │
3. │           3 │ Carol │ Rome   │       1 │ 2026-03-01 00:00:00 │
   └─────────────┴───────┴────────┴─────────┴─────────────────────┘
```

The end of a validity interval is the start of the next version. The [`lead`](https://clickhouse.com/docs/reference/functions/window-functions/lead) window function computes it at query time, and the current version has no end:

```sql theme={null}
SELECT
    customer_id,
    name,
    city,
    version,
    valid_from,
    lead(toNullable(valid_from)) OVER (PARTITION BY customer_id ORDER BY version) AS valid_to
FROM customers_history
ORDER BY customer_id, version;
```

```text theme={null}
   ┌─customer_id─┬─name──┬─city───┬─version─┬──────────valid_from─┬────────────valid_to─┐
1. │           1 │ Alice │ Berlin │       1 │ 2026-01-01 00:00:00 │ 2026-03-01 00:00:00 │
2. │           1 │ Alice │ Madrid │       2 │ 2026-03-01 00:00:00 │ 2026-04-01 00:00:00 │
3. │           1 │ Alice │ Berlin │       3 │ 2026-04-01 00:00:00 │                ᴺᵁᴸᴸ │
4. │           2 │ Bob   │ Paris  │       1 │ 2026-01-01 00:00:00 │                ᴺᵁᴸᴸ │
5. │           3 │ Carol │ Rome   │       1 │ 2026-03-01 00:00:00 │                ᴺᵁᴸᴸ │
   └─────────────┴───────┴────────┴─────────┴─────────────────────┴─────────────────────┘
```

To join facts with the version of the dimension that was valid when the fact happened, use [`ASOF JOIN`](https://clickhouse.com/docs/reference/statements/select/join#asof-join-usage). It needs only `valid_from`, which must be different for every version of a key (see [Limitations](#limitations)):

```sql theme={null}
CREATE TABLE orders
(
    order_id UInt32,
    customer_id UInt32,
    ordered_at DateTime('UTC')
)
ENGINE = MergeTree
ORDER BY order_id;

INSERT INTO orders VALUES
    (101, 1, '2026-01-15 10:00:00'),
    (102, 1, '2026-03-10 12:30:00'),
    (103, 1, '2026-04-20 09:15:00'),
    (104, 3, '2026-03-05 18:45:00');

SELECT o.order_id, o.ordered_at, c.name, c.city, c.version
FROM orders AS o
ASOF LEFT JOIN customers_history AS c
    ON o.customer_id = c.customer_id AND o.ordered_at >= c.valid_from
ORDER BY o.order_id;
```

```text theme={null}
   ┌─order_id─┬──────────ordered_at─┬─name──┬─city───┬─version─┐
1. │      101 │ 2026-01-15 10:00:00 │ Alice │ Berlin │       1 │
2. │      102 │ 2026-03-10 12:30:00 │ Alice │ Madrid │       2 │
3. │      103 │ 2026-04-20 09:15:00 │ Alice │ Berlin │       3 │
4. │      104 │ 2026-03-05 18:45:00 │ Carol │ Rome   │       1 │
   └──────────┴─────────────────────┴───────┴────────┴─────────┘
```

## Limitations

* **One writer at a time.** The view reads `customers_history` and then writes to it, and inserts do not lock each other. Two concurrent loads of the same key can both read the same latest version and both store the next number. `ReplacingMergeTree` then keeps only the row inserted last (after a merge, or immediately with `FINAL`), so one of the two changes is lost. Run the loads of a dimension one after another.
* **One row per key in an insert.** Rows of the same key in one insert all compare with the same stored version and get the same number, and only the last of them is kept. If a batch can contain several changes of a key, send them in separate inserts, oldest first.
* **Changes must arrive in order.** The view appends after the latest stored version. A late row with an older `updated_at` becomes the newest version.
* **Two versions of a key must not have the same `valid_from`.** With `DateTime`, this happens when a key changes twice within one second. The interval query then gives the earlier version an empty interval, but `ASOF JOIN` compares only `valid_from` and can return either of the two versions. If the source can send such changes, store `updated_at` and `valid_from` as `DateTime64` with the precision of the source, or join with a subquery that keeps only the latest version for each `valid_from`: `(SELECT * FROM customers_history ORDER BY version DESC LIMIT 1 BY customer_id, valid_from) AS c`.
* **The tracked attributes are listed twice**, in `row_hash` and in the `WHERE` clause of the view. Keep the two expressions identical when you add an attribute.
* **Deletions are not recorded.** A key that disappears from the source keeps its last version. To track deletions, have the source send a row with a flag column and include that column in the hash.
* **Every insert runs a lookup** in `customers_history` for the keys of the inserted block. Prefer a few large loads to many small inserts.
