What are slowly changing dimensions, and how would you test their history rules?
Answer
A slowly changing dimension defines how warehouse attributes are handled when a business entity changes, such as overwriting the current value or creating a dated historical row. Test unchanged, first-time, repeated, backdated and multiple changes while checking surrogate keys, effective dates, current-row flags and joins from facts to the correct version. Rerunning the same load must not create duplicate history, and reports for past dates should retain the intended historical meaning.
Strong answer includes
- distinguishes overwrite and history-preserving behavior
- checks effective dates, current flags and surrogate keys
- verifies idempotency and historical reporting
Practical example
Requires a Type 2 dim_customer history table; the example assumes valid_to is an exclusive end boundary.
WITH history AS (
SELECT
customer_id,
valid_from,
valid_to,
is_current,
LEAD(valid_from) OVER (
PARTITION BY customer_id
ORDER BY valid_from
) AS next_valid_from
FROM dim_customer
)
SELECT *
FROM history
WHERE next_valid_from IS NOT NULL
AND (valid_to IS NULL OR valid_to > next_valid_from);
SELECT customer_id,
SUM(CASE WHEN is_current = TRUE THEN 1 ELSE 0 END) AS current_rows
FROM dim_customer
GROUP BY customer_id
HAVING SUM(CASE WHEN is_current = TRUE THEN 1 ELSE 0 END) <> 1;Assuming half-open validity ranges [valid_from, valid_to), Type 2 history should not overlap and each tracked entity should have exactly one current version. Aggregating all history rows, rather than filtering to current rows first, allows the second check to detect both zero and multiple current versions.
Expected result: Both validation queries return zero rows for a consistent Type 2 dimension.