← Back to SQL, page 18

sql-0355 · Hard senior

A customer moves city. How would a reporting dimension keep both the old and new city for historical sales?

Use a type 2 slowly changing dimension: instead of updating the customer row, close it with an end date and insert a new row with a new surrogate key, the new city and a start date. Facts recorded before the move keep pointing at the old row, so historical reports show the city at the time of sale.

Full answer
text
dim_customer(customer_key PK, customer_id, city, valid_from, valid_to, is_current)

When the customer moves on 2026-03-01:

  1. UPDATE dim_customer SET valid_to = '2026-02-28', is_current = false WHERE customer_id = 7 AND is_current;
  2. INSERT INTO dim_customer (customer_id, city, valid_from, valid_to, is_current) VALUES (7, 'Leeds', '2026-03-01', '9999-12-31', true);

New sales are loaded with the current customer_key. Reports grouped by city then attribute February sales to the old city and March sales to the new one.

Other types: type 1 overwrites (no history), type 3 adds a 'previous city' column (one step of history). Type 2 is the usual choice when attributes affect reporting. A unique partial index on customer_id WHERE is_current keeps one current row per customer.

Key points

  • Type 2 adds a new row per change
  • Surrogate keys link facts to the version at the time
  • valid_from, valid_to and is_current track versions
  • Type 1 overwrites, type 3 keeps one previous value

Common mistakes

  • Updating the city in place and rewriting history
  • Joining facts on the natural key instead of the surrogate key

Follow-ups

  • How would you query a customer's city on a given date?
  • Which attributes deserve type 2 tracking?

Tips

  • Show the close-and-insert step