Dimension data is not frozen. A customer changes city, a product moves to another category, an employee changes team. Slowly changing dimensions (SCD) are the standard answers to a simple question: when a value changes, do we care about the old one?
Type 0 and type 1: do not keep history
Type 0 never changes a value once written, for example a date of birth. Type 1 overwrites the old value with the new one.
UPDATE dim_customer SET city = 'Da Nang' WHERE customer_id = 42;Type 1 is simple and keeps the table small. The price is that history is gone: last year's sales are now reported under the new city, as if the customer had always lived there.
Type 2: keep every version
Type 2 adds a new row for each change and records the period during which each row was valid.
CREATE TABLE dim_customer (
customer_key bigserial PRIMARY KEY, -- surrogate key, one per version
customer_id bigint NOT NULL, -- natural key from the source
city text,
valid_from date NOT NULL,
valid_to date, -- null while current
is_current boolean NOT NULL DEFAULT true
);When the customer moves, you close the current row by setting valid_to and is_current = false, then insert a new row. Facts point to the surrogate key that was current when the event happened, so old sales stay with the old city.
Querying history
- For current values, filter on
is_current = true. - For a point in time, filter on
valid_from <= date AND (valid_to IS NULL OR date < valid_to).
Type 3 and others
Type 3 adds a "previous value" column, which remembers one change only. Rare variations combine approaches, for example keeping type 2 history for some columns and type 1 for others.
Choosing
- Use type 1 for corrections, such as fixing a typo, and for attributes nobody reports historically.
- Use type 2 when the business asks "what was true at the time?", for example sales by the region a salesperson belonged to then.
Takeaway
Decide per attribute, not per table. Ask whether the business needs history, and write the decision down so that reports mean the same thing next year.
Comments