Keeping history

Part of the free LogicWiz Data Engineering course, Module 5: Data modelling. The SQL and Python run in the app, on real Postgres and real Python in the browser.

It is 9:20 on 10 June. Tess reruns yesterday's report, "June revenue by city", on the shop's database. Berlin is $54 lower than it was yesterday. No order was cancelled. Nothing was refunded. Nora asks one question: "Did an order change, or did a customer?"

You'll learn to

  • Choose type 1, 2 or 3 for a column that changes
  • Query history "as it was" and "as it is"
  • Load a type 2 change, and say what it costs on files
  • Handle an order that arrives before its customer

Learn

The app overwrote his city

A customer changed. Jonas Weber (customer 18) moved from Berlin to Munich on 9 June, and Dana's app replaced his city. So his 7 June order, $54, now reports under Munich.

The warehouse has to remember. A table whose details change now and then is called a slowly changing dimension (SCD), and there are three classic ways to handle a change. Think of a paper address book:

  • Type 1, overwrite: rub out Berlin, write Munich. No history. Right for fixing a typo in a name.
  • Type 2, add a row: keep the Berlin line, add a Munich line, date both. Full history.
  • Type 3, add a column: keep previous_city next to city. One step of history only.

Jonas moves, three ways

A customer who moves from Berlin to Munich, shown as a type 1, a type 2 and a type 3 dimension table along a timeline, with each order pointing at the version in force that day.

Pick a type, then drag As of past 9 June. Watch which city each of his four orders reports: only type 2 gets every order right.

Type 2: one row per version

SwiftKart picks type 2 for city. The dimension now holds one row per version of a customer, and four columns make that work:

  • customer_key: a new surrogate key (Lesson 5.1) for each version. The natural key customer_id repeats.
  • valid_from: the day this version became true.
  • valid_to: the day it stopped being true. The current version gets a far-future date, 9999-12-31, not NULL, so date checks stay easy.
  • is_current: true on the one row in force today.

One detail matters more than the rest: valid_to is exclusive. The Berlin row ends on 2025-06-09 and the Munich row starts that same day. So on the change day exactly one row matches valid_from <= day AND day < valid_to.

Jonas moves through dim_customer

Customer 18 in a type 2 dimension, step by step: one Berlin row, the Berlin row closed on 9 June, a Munich row added with a new key, and later orders pointing at the new key while the 7 June order keeps the old one.

  1. 8 June, before the move. Jonas has one row: key 18, Berlin, with an open end date. His 7 June order stores customer_key 18.

  2. 9 June: close the old row. The nightly load sees Munich. It does not overwrite Berlin. It ends the Berlin row: valid_to becomes 2025-06-09 and is_current becomes false.

  3. Then add the new version. A second row goes in with a new key, 19: Munich, valid from 2025-06-09, current. Nobody touched the 7 June order. It still points at key 18.

  4. New orders take the new key. His orders of 9, 10 and 12 June store key 19. Join on the key and Berlin keeps $54.00, while Munich gets $314.76.

Read each step top to bottom: the dimension rows, then the orders and the key each one stores.

Two versions, and the orders behind each

SELECT c.customer_key, c.city, c.valid_from, c.valid_to, c.is_current,
  COUNT(f.line_no) AS lines,
  COALESCE(SUM(f.line_amount), 0) AS revenue
FROM dim_customer c
LEFT JOIN fact_order_line f ON f.customer_key = c.customer_key
WHERE c.customer_id = 18
GROUP BY c.customer_key, c.city, c.valid_from, c.valid_to, c.is_current
ORDER BY c.valid_from;

Each fact row stores the customer_key that was in force on its order date. So a plain join on the key reports every order under the city of its day: Berlin $54.00, Munich $314.76.

Remember: type 2 keeps the old row. It gives it an end date, adds a new row with a new key, and each order keeps the key of its own day.

As it was, or as it is?

Tess now has two honest answers to "revenue by city", and they differ.

  • As it was: join the fact on customer_key. The 7 June order counts for Berlin. This is what "revenue by city in June" usually means.
  • As it is: go through the natural key to today's row, so every order counts under the customer's current city. Good for "where do our current customers live, and what have they bought?"
JOIN dim_customer v   ON v.customer_key = f.customer_key
JOIN dim_customer cur ON cur.customer_id = v.customer_id
                     AND cur.is_current

When someone asks for "revenue by city", ask which one they mean.

One customer, two right answers

Jonas's orders on the left point at the Berlin and Munich versions in the middle, giving $54.00 and $314.76 as it was; both versions then lead to the current Munich row on the right, giving $368.76 as it is.

Read it left to right. Stop at the middle column for "as it was". Follow the dashed arrows to today's row for "as it is": the same four orders, all under Munich.

Find the version for a date

Sometimes the incoming rows carry only the natural key: a staging table of new orders, an event stream, a partner's file. They have a customer_id and a date, but no customer_key yet.

To find the right version, join on the natural key and ask which row's dates contain the order date:

JOIN dim_customer c
  ON c.customer_id = o.customer_id
 AND o.order_date >= c.valid_from
 AND o.order_date <  c.valid_to

This is a point-in-time join: "give me the version that was true at that moment". A loader uses it to pick the customer_key for each new fact row. Machine learning teams use it to build training data without leaking facts from the future.

Which row is true on which day

A timeline of June: the Berlin row is valid up to 9 June, the Munich row from 9 June on, and Jonas's four orders sit on 7, 9, 10 and 12 June, with the 9 June order under the Munich row only.

Each bar is one row's life (the Berlin row began on 1 January), and the dashed line is the move. The order placed on 9 June sits under Munich only.

Give each new order the right version

SELECT o.order_id, o.order_date, c.customer_key, c.city
FROM stg_orders o
JOIN dim_customer c
  ON c.customer_id = o.customer_id
 AND o.order_date >= c.valid_from
 AND o.order_date < c.valid_to
ORDER BY o.order_id;

stg_orders (made for this card) carries customer_id only. Order 2001 (8 June) gets the Berlin key 18. Order 2002, placed on the day of the move, gets the Munich key 19.

The change day is where type 2 bugs hide. BETWEEN valid_from AND valid_to includes both ends, so on 9 June both of Jonas's rows match and his order counts twice. Write >= valid_from AND < valid_to. Then test every type 2 dimension for two things: exactly one current row per natural key, and no overlapping ranges.

Load a change: close, then insert

Now build the load. Each night the source sends today's customers. For every customer whose tracked columns changed, the load does two things:

  1. Close the current row: valid_to = the change date, is_current = false.
  2. Insert the new version with a new key: valid_from = the change date, valid_to = 9999-12-31, is_current = true.

Brand-new customers get step 2 only. Unchanged customers are left alone.

Compare old and new with IS DISTINCT FROM, not <>: NULL <> 'x' is NULL, not true, so an email filled in where there was none would slip through. Run both steps in one transaction, so nobody sees a customer with no current row.

Close, then insert

BEGIN;

-- 1. close the current row of every changed customer
UPDATE dim_customer d
SET valid_to = DATE '2025-06-12', is_current = false
FROM stg_customer s
WHERE s.customer_id = d.customer_id
  AND d.is_current
  AND (s.city IS DISTINCT FROM d.city OR s.email IS DISTINCT FROM d.email);

-- 2. add a current row for everyone who now has none: changed and new customers
INSERT INTO dim_customer (customer_key, customer_id, name, email, city, country,
                          signup_date, valid_from, valid_to, is_current)
SELECT (SELECT MAX(customer_key) FROM dim_customer)
         + ROW_NUMBER() OVER (ORDER BY s.customer_id),
       s.customer_id, s.name, s.email, s.city, s.country,
       s.signup_date, DATE '2025-06-12', DATE '9999-12-31', true
FROM stg_customer s
LEFT JOIN dim_customer d ON d.customer_id = s.customer_id AND d.is_current
WHERE d.customer_id IS NULL;

COMMIT;

SELECT customer_key, customer_id, city, valid_from, valid_to, is_current
FROM dim_customer
WHERE customer_id IN (4, 31)
ORDER BY customer_id, valid_from;

stg_customer (made for this card) is the 12 June export: Ken Watanabe (customer 4) moved to Osaka and Ana Lima (31) is new. After step 1 a changed customer has no current row, so one LEFT JOIN ... IS NULL in step 2 finds changed and new customers alike.

dim_customer before and after the load

Whencustomerkeycustomeridcityvalidfromvalidtoiscurrent
before44Tokyo2025-01-019999-12-31true
after44Tokyo2025-01-012025-06-12false
after324Osaka2025-06-129999-12-31true
after3331Porto2025-06-129999-12-31true

The old row is never deleted: only its end date and its flag change. Older facts keep pointing at key 4, so Tokyo keeps its history.

The same load as one MERGE

CREATE SEQUENCE customer_key_seq;
SELECT setval('customer_key_seq', (SELECT MAX(customer_key) FROM dim_customer));

MERGE INTO dim_customer d
USING (
  SELECT s.customer_id AS merge_id, s.* FROM stg_customer s
  UNION ALL
  SELECT NULL, s.*                       -- a second copy of each changed row
  FROM stg_customer s
  JOIN dim_customer cur ON cur.customer_id = s.customer_id AND cur.is_current
  WHERE s.city IS DISTINCT FROM cur.city OR s.email IS DISTINCT FROM cur.email
) src
ON d.customer_id = src.merge_id AND d.is_current
WHEN MATCHED AND (src.city IS DISTINCT FROM d.city OR src.email IS DISTINCT FROM d.email) THEN
  UPDATE SET valid_to = DATE '2025-06-12', is_current = false
WHEN NOT MATCHED THEN
  INSERT (customer_key, customer_id, name, email, city, country, signup_date, valid_from, valid_to, is_current)
  VALUES (nextval('customer_key_seq'), src.customer_id, src.name, src.email, src.city, src.country,
          src.signup_date, DATE '2025-06-12', DATE '9999-12-31', true);

SELECT customer_id, city, valid_from, valid_to, is_current
FROM dim_customer
WHERE customer_id IN (4, 31)
ORDER BY customer_id, valid_from;

One MERGE cannot both update and insert for the same source row. So the trick feeds each changed customer in twice: once with its id (it matches and closes the old row) and once with a NULL id (it never matches, so it goes in as the new version). The same pattern is common with Delta Lake on Databricks. Keep one row per customer in the source: a MERGE may update a row only once.

On a lakehouse, one change rewrites a file

Postgres changed two rows in place. A lakehouse or a cloud warehouse cannot do that. Its data sits in column files that are immutable: once written, a file is never edited, only replaced. Think of a printed page: to fix one word, you print the page again.

So when a MERGE changes a few rows in a Delta Lake file, it rewrites the whole file, every unchanged row included. Snowflake does the same with its files, called micro-partitions.

The cost of a type 2 load is therefore not the number of changed rows. It is the number of files those rows happen to live in. And changed customers are scattered at random across the table, because nobody moves city in customer_id order.

What a Delta MERGE does to the files

Four steps of a Delta Lake MERGE: join the source to the target to find the files with matching rows, rewrite each of those files with its unchanged and updated rows, write the inserted rows to new files, then commit one log entry that removes the old files and adds the new ones.

Read it left to right. Step 1 is a join over the whole table unless the ON clause narrows it (a partition or date condition). Step 2 is where the bytes go.

The sum, one line at a time

StepSumResult
The table50M rows × about 200 bytes10 GB
Its files10 GB / 125 MB a file80 files
One night of changes0.2% of 50M customers100,000 rows, about 20 MB
Files that hold a changed row80 × (1 − (1 − 1/80)^100,000)all 80
Bytes rewritten80 files × 125 MB10 GB, to change 20 MB

If k changes land at random in F files, the expected number of files touched is F × (1 − (1 − 1/F)^k). Even 50 changes touch about 37 of the 80 files.

Bytes written by one nightly type 2 load

Bars compare the bytes written to apply 100,000 customer changes: 10,000 MB when every touched file is rewritten, 40 MB with deletion vectors, against 20 MB for the changed rows themselves.

Same data, same result. A deletion vector marks the old rows as removed instead of rewriting their files. The cost moves to reads (the reader skips marked rows) until OPTIMIZE or REORG TABLE ... APPLY (PURGE) rewrites the files.

When the order arrives before the customer

One last case. An order arrives at 09:00 for customer 40, but the CRM export that holds customer 40 lands tomorrow. The point-in-time join finds no row. Three options:

  • Park the fact in a suspense table and retry. Revenue goes missing until it loads.
  • Point it at an "Unknown" row (key -1). The revenue counts, but it belongs to nobody unless you reprocess.
  • Create a placeholder: a row with the natural key, a new surrogate key and is_inferred = true. Load the fact against it. When the real row arrives, fill the placeholder in place (a type 1 fill, not a new version).

The placeholder is called an inferred member. It is the usual choice: nothing is lost and nothing is reloaded.

A placeholder now, the real customer tomorrow

-- 1. a placeholder for every customer the new facts mention but the dimension lacks
INSERT INTO dim_customer (customer_key, customer_id, name, email, city, country,
                          signup_date, valid_from, valid_to, is_current, is_inferred)
SELECT (SELECT MAX(customer_key) FROM dim_customer)
         + ROW_NUMBER() OVER (ORDER BY s.customer_id),
       s.customer_id, 'Unknown', NULL, 'Unknown', 'Unknown',
       MIN(s.order_date), MIN(s.order_date), DATE '9999-12-31', true, true
FROM stg_order_line s
WHERE NOT EXISTS (SELECT 1 FROM dim_customer d WHERE d.customer_id = s.customer_id)
GROUP BY s.customer_id;

-- 2. now every fact row finds a key
INSERT INTO fact_order_line (order_id, line_no, date_key, customer_key, product_key,
                             status, qty, unit_price, line_amount)
SELECT s.order_id, s.line_no, TO_CHAR(s.order_date, 'YYYYMMDD')::INT, c.customer_key,
       s.product_key, 'placed', s.qty, s.unit_price, s.qty * s.unit_price
FROM stg_order_line s
JOIN dim_customer c
  ON c.customer_id = s.customer_id
 AND s.order_date >= c.valid_from
 AND s.order_date < c.valid_to;

-- 3. the next night the CRM row arrives: fill the placeholder in place
UPDATE dim_customer
SET name = 'Lena Novak', email = '[email protected]', city = 'Prague',
    country = 'Czechia', signup_date = DATE '2025-06-12', is_inferred = false
WHERE customer_id = 40 AND is_inferred;

SELECT f.order_id, f.line_no, c.customer_key, c.name, c.city, c.is_inferred
FROM fact_order_line f
JOIN dim_customer c ON c.customer_key = f.customer_key
WHERE f.order_id > 2100
ORDER BY f.order_id, f.line_no;

The setup added is_inferred to dim_customer and staged three order lines; customer 40 is not in the dimension yet. Both lines of order 2101 point at key 32, which said "Unknown" when they loaded and says Lena in Prague now. Step 3 touched no fact row.

Numbers to remember

ThingValueWhat it is
validto of a current row9999-12-31a far-future date, not NULL
Comparing old and newIS DISTINCT FROMNULL counts as a value; many teams compare one hash of the tracked columns
The "Unknown" rowkey -1for a fact whose customer is missing, when you add no placeholder
Files a MERGE touchesF × (1 − (1 − 1/F)^k)k changes at random in F files: 50 changes in 80 files touch about 37
Deletion vectors (Delta)opt-in per table or by workspace settingabout 40 MB written in the example, not 10 GB
Snowflakemicro-partitionsre-created on a change; old ones stay billed as Time Travel and Fail-safe storage for days
Two source rows for one customerthe MERGE failsPostgres: MERGE command cannot affect row a second time. Delta: DELTAMULTIPLESOURCEROWMATCHINGTARGETROWINMERGE
Tools that write this loaddbt snapshots (Module 8)on Databricks, Lakeflow Declarative Pipelines (formerly Delta Live Tables): AUTO CDC ... STORED AS SCD TYPE 2 (older code says APPLY CHANGES)

Few teams hand-write this load every time, but the tool runs what you ran above.

What changed at SwiftKart

dim_customer is now type 2 on city and email. Jonas has two rows, his 7 June order still points at the Berlin one, and Tess's Berlin number has its $54 back.

For the day this table grows on a lakehouse, Nora writes down three fixes for the rewrite cost: turn on deletion vectors, cluster the table by is_current so a close touches only current-row files and never years of history, and shrink the source by merging only real changes.

Next, Lesson 5.5: Dana's rule is "never store the same fact twice". The analysts want one wide table with everything on every row. Who is right?

In one line

Type 2 keeps history: each version gets its own key and dates (end exclusive), each order keeps the key of its own day, and a load closes the old row, then adds the new one.

Interview corner

Explain SCD types 1, 2 and 3.

Type 1 overwrites the attribute, so there is no history; it suits corrections. Type 2 closes the current row and inserts a new version with its own surrogate key and validity dates, keeping full history. Type 3 adds a column such as previous_city, keeping only one step back.

How do you load a type 2 dimension?

Compare the incoming snapshot with the current rows on the tracked columns, using IS DISTINCT FROM or a hash so NULLs count. Close changed rows by setting valid_to to the change date and is_current to false, then insert new current rows for changed and brand-new keys, in one transaction. In Postgres or Delta this can be one MERGE with the changed rows fed in twice.

What is a point-in-time join and where would you use one?

It joins on the natural key and a date range, valid_from <= event_date < valid_to, to pick the version that was true when the event happened. A fact loader uses it to give each new row the right surrogate key, and ML teams use it to build training data without leaking later values.

Your nightly type 2 MERGE on a 50-million-row Delta dimension rewrites the whole table although only 0.2% of customers change. Why, and what do you do?

Delta rewrites every file that holds a matched row, unchanged rows included, and 100,000 changes scattered over 80 files touch all of them: about 10 GB written to change 20 MB. I would enable deletion vectors so matched rows are only marked, cluster the table by is_current so closes never touch history files, and filter the source to rows whose tracked-column hash changed. I would also add a partition or clustering predicate to the ON clause so the first join does not scan everything.