Skip to content

Data engineering basics · Part 8 of 10

Slowly changing dimensions: what to do when a customer moves

Attributes such as a customer's city change over time. SCD types decide whether you overwrite the old value or keep history. Type 1 and type 2 explained.

· 2 min read

data-engineeringmodeling

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.

SQL
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.

SQL
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.

A knowledge article, drafted with AI assistance and checked with automated tests. It is general background, not a description of my own experience or of any client's work.

Comments

Leave a comment

No account or email needed. Comments appear after review. A one-way hash of your IP address is kept for 30 days to fight spam, then erased.