Slowly changing dimension type 2 (SCD2) in SQL
When a customer moves and their past orders must stay in the old city, overwriting the row (type 1) rewrites history. Type 2 keeps one row per version instead: a change closes the current version and opens a new one, each with its own surrogate key.
-- customer 7 moves to York on 15 November 2025
UPDATE dim_customer
SET valid_to = DATE '2025-11-14', is_current = FALSE
WHERE customer_id = 7 AND is_current;
INSERT INTO dim_customer (customer_key, customer_id, city, valid_from, valid_to, is_current)
VALUES (2, 7, 'York', DATE '2025-11-15', NULL, TRUE);
-- the version valid on a given day
SELECT * FROM dim_customer
WHERE DATE '2025-06-30' BETWEEN valid_from AND COALESCE(valid_to, DATE '9999-12-31');
The trap. Mixing up the two conventions for the end of a version. Here valid_to is the last day, so test with
BETWEEN; when it holds the next version's start (half-open), test valid_from <= d AND d < valid_to. Mix them and
every change loses or doubles a day; forget the COALESCE and every current version disappears.
In dbt. A snapshot builds this table for you: strategy: timestamp on an updated_at column, or
strategy: check on a list of check_cols, with a unique_key. It adds dbt_valid_from and dbt_valid_to,
half-open, with dbt_valid_to NULL for the current version by default: there, is_current is
dbt_valid_to IS NULL.
WITH versions(customer_id, city, valid_from) AS (VALUES
(7, 'Leeds', DATE '2024-03-02'),
(7, 'York', DATE '2025-11-15'),
(8, 'Lyon', DATE '2024-06-10'))
SELECT customer_id, city, valid_from,
LEAD(valid_from) OVER (PARTITION BY customer_id ORDER BY valid_from) - 1 AS valid_to,
LEAD(valid_from) OVER (PARTITION BY customer_id ORDER BY valid_from) IS NULL AS is_current
FROM versions
ORDER BY customer_id, valid_from;
| customer_id | city | valid_from | valid_to | is_current |
|---|---|---|---|---|
| 7 | Leeds | 2024-03-02 | 2025-11-14 | false |
| 7 | York | 2025-11-15 | NULL | true |
| 8 | Lyon | 2024-06-10 | NULL | true |
WITH dim_customer(customer_key, customer_id, city, valid_from, valid_to) AS (VALUES (1, 7, 'Leeds', DATE '2024-03-02', DATE '2025-11-14'), (2, 7, 'York', DATE '2025-11-15', NULL), (3, 8, 'Lyon', DATE '2024-06-10', NULL)), sales(order_id, customer_id, ordered_on) AS (VALUES (101, 7, DATE '2025-06-30'), (102, 7, DATE '2025-11-15'), (103, 8, DATE '2025-12-01')) SELECT s.order_id, s.ordered_on, d.customer_key, d.city FROM sales s JOIN dim_customer d ON d.customer_id = s.customer_id AND s.ordered_on BETWEEN d.valid_from AND COALESCE(d.valid_to, DATE '9999-12-31') ORDER BY s.order_id;
| order_id | ordered_on | customer_key | city |
|---|---|---|---|
| 101 | 2025-06-30 | 1 | Leeds |
| 102 | 2025-11-15 | 2 | York |
| 103 | 2025-12-01 | 3 | Lyon |