Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 5 of 6 · Lab · 30 min · revision 2

Lab: Type 2 History and Point-in-Time Joins

In PostgreSQL 17, build a customer dimension that overwrites corrections (Type 1) and versions moves and segment changes (Type 2) from daily CRM snapshots, load facts with a point-in-time key lookup that also handles a late order, report revenue as it was and as it is, and test the dimension.

Contentsand lesson path

What you will learn

  • Implement Type 1 and Type 2 slowly changing dimensions and join facts to the dimension version valid at event time.

Prerequisites: Relational Data Modeling

01. Goal and setup

Dimension attributes change: customers move, change segment, fix the spelling of their names. A slowly changing dimension (SCD) is a dimension with a rule, chosen per attribute, for what happens when a value changes. The two rules you will use most are:

  • Type 1: overwrite the value. History is lost, which is right for corrections, such as a misspelt name.
  • Type 2: keep the old row, close it, and add a new row (a new version) with a new surrogate key and a validity period. History is kept, which is right when reports must show facts under the value that was true at the time, such as the city a customer lived in when they ordered.

In this lab you build a customer dimension with both rules from three daily CRM snapshots, then load orders so that each one points to the version valid when it was placed: a point-in-time lookup. You finish with two reports that answer different questions from the same facts, and with tests that guard the dimension.

You need the sql-lab container (PostgreSQL 17; tested with 17.11) from earlier lessons and a folder scd-lab/. The lab builds on the retail star schema.

Folder layout at the end of the lab
scd-lab/
├── seed.sql      step 1: CRM snapshots and source orders
├── dim.sql       step 2: dimension table and loader procedure
├── load.sql      step 3: three daily loads and a re-run
├── fact.sql      step 4: point-in-time fact load
├── report.sql    step 5: revenue as it was and as it is
└── test.sql      step 6: tests for the dimension

02. Step 1: Load the CRM snapshots and the orders

The CRM sends a full copy of its customer table every few days; each copy is a snapshot. Between 1 and 5 March, Ana moved from Leeds to York, the misspelt "Ben Ode" was corrected to "Ben Odé", and Cai joined. By 9 March Ana had moved from the Retail to the Trade segment. Order 6 was placed on 4 March on an offline till and reached the warehouse days later, a late-arriving fact.

SQL · seed.sql
CREATE TABLE crm_snapshot (       -- one full copy of the CRM customer table per day
  snapshot_date date, customer_id text, name text, city text, segment text,
  PRIMARY KEY (snapshot_date, customer_id)
);
INSERT INTO crm_snapshot VALUES
  ('2026-03-01', 'C1', 'Ana Smith', 'Leeds', 'Retail'),
  ('2026-03-01', 'C2', 'Ben Ode',   'York',  'Trade'),
  ('2026-03-05', 'C1', 'Ana Smith', 'York',  'Retail'),   -- Ana moved
  ('2026-03-05', 'C2', 'Ben Odé',   'York',  'Trade'),    -- typo fixed
  ('2026-03-05', 'C3', 'Cai Lee',   'Bath',  'Retail'),   -- new customer
  ('2026-03-09', 'C1', 'Ana Smith', 'York',  'Trade'),    -- Ana changed segment
  ('2026-03-09', 'C2', 'Ben Odé',   'York',  'Trade'),
  ('2026-03-09', 'C3', 'Cai Lee',   'Bath',  'Retail');
CREATE TABLE src_orders (order_id int PRIMARY KEY, customer_id text,
                         ordered_at timestamp, amount numeric(8,2));
INSERT INTO src_orders VALUES
  (1, 'C1', '2026-03-02 10:00', 50), (2, 'C2', '2026-03-03 12:00', 80),
  (3, 'C1', '2026-03-06 09:00', 30), (4, 'C3', '2026-03-07 15:00', 20),
  (5, 'C1', '2026-03-10 11:00', 70),
  (6, 'C1', '2026-03-04 16:00', 40);  -- arrived late, from an offline till
SELECT snapshot_date, count(*) AS customers FROM crm_snapshot
GROUP BY 1 ORDER BY 1;
Terminal
docker exec sql-lab psql -U postgres -X -q -c "SET client_min_messages = warning" \
  -c "DROP DATABASE IF EXISTS dw" -c "CREATE DATABASE dw"
docker exec -i sql-lab psql -U postgres -d dw -X -q < seed.sql
Expected output
 snapshot_date | customers 
---------------+-----------
 2026-03-01    |         2
 2026-03-05    |         3
 2026-03-09    |         3
(3 rows)

03. Step 2: Create the dimension and its loader

Each row of dim_customer is one version of a customer. customer_id is the natural key and repeats across versions; customer_key is the surrogate key and is unique per version. valid_from and valid_to mark when the version was true. The interval is half-open: it includes valid_from and excludes valid_to, so the old version ends exactly where the new one starts and no instant belongs to two versions. The current version has valid_to = 9999-12-31, a far-future date that avoids NULL in comparisons, and is_current = true. A partial unique index makes the database itself refuse a second current row for one customer.

The procedure applies one snapshot, in three statements:

  1. Type 1 first. Overwrite name on every version of the customer, so old facts also show the corrected spelling.
  2. Close the current version of every customer whose Type 2 attributes, city or segment, differ from the snapshot. IS DISTINCT FROM compares the pair and treats NULLs as values.
  3. Open a version for every customer in the snapshot who now has no current row: those just closed in statement 2, and new customers. A brand-new customer's first version starts at 1900-01-01, so that facts dated before the customer's first snapshot still find it.

The new version starts on the snapshot date. The real change happened at some point since the previous snapshot, and the dimension cannot know when; that is the price of daily snapshots instead of a change feed.

SQL · dim.sql
CREATE TABLE dim_customer (
  customer_key int GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  customer_id  text NOT NULL,                   -- natural key
  name         text NOT NULL,                   -- Type 1: overwrite
  city         text NOT NULL,                   -- Type 2: keep history
  segment      text NOT NULL,                   -- Type 2: keep history
  valid_from   date NOT NULL,
  valid_to     date NOT NULL DEFAULT '9999-12-31',  -- exclusive
  is_current   boolean NOT NULL DEFAULT true
);
CREATE UNIQUE INDEX one_current_row ON dim_customer (customer_id) WHERE is_current;

CREATE PROCEDURE load_dim_customer(p_date date)
LANGUAGE plpgsql
AS $$
BEGIN
  -- 1. Type 1 attributes: overwrite on every version
  UPDATE dim_customer d SET name = s.name
  FROM crm_snapshot s
  WHERE s.snapshot_date = p_date AND s.customer_id = d.customer_id
    AND d.name IS DISTINCT FROM s.name;

  -- 2. Type 2 attributes changed: close the current version
  UPDATE dim_customer d SET valid_to = p_date, is_current = false
  FROM crm_snapshot s
  WHERE s.snapshot_date = p_date AND s.customer_id = d.customer_id
    AND d.is_current
    AND (d.city, d.segment) IS DISTINCT FROM (s.city, s.segment);

  -- 3. New customers, and customers closed in step 2: open a new version
  INSERT INTO dim_customer (customer_id, name, city, segment, valid_from)
  SELECT s.customer_id, s.name, s.city, s.segment,
         CASE WHEN EXISTS (SELECT 1 FROM dim_customer h
                           WHERE h.customer_id = s.customer_id)
              THEN p_date ELSE date '1900-01-01' END
  FROM crm_snapshot s
  WHERE s.snapshot_date = p_date
    AND NOT EXISTS (SELECT 1 FROM dim_customer d
                    WHERE d.customer_id = s.customer_id AND d.is_current);
  COMMIT;
END;
$$;
Terminal
docker exec -i sql-lab psql -U postgres -d dw -X -q < dim.sql && echo created
Expected output
created

04. Step 3: Load three snapshots and read the history

Apply the snapshots in date order, then apply the last one a second time: a loader that a scheduler may retry must not create versions when nothing changed.

SQL · load.sql
CALL load_dim_customer('2026-03-01');
CALL load_dim_customer('2026-03-05');
CALL load_dim_customer('2026-03-09');
CALL load_dim_customer('2026-03-09');   -- a re-run must change nothing

SELECT customer_key AS key, customer_id AS id, name, city, segment,
       valid_from, valid_to, is_current AS cur
FROM dim_customer ORDER BY customer_id, valid_from;
Terminal
docker exec -i sql-lab psql -U postgres -d dw -X -q < load.sql
Expected output
 key | id |   name    | city  | segment | valid_from |  valid_to  | cur 
-----+----+-----------+-------+---------+------------+------------+-----
   1 | C1 | Ana Smith | Leeds | Retail  | 1900-01-01 | 2026-03-05 | f
   3 | C1 | Ana Smith | York  | Retail  | 2026-03-05 | 2026-03-09 | f
   5 | C1 | Ana Smith | York  | Trade   | 2026-03-09 | 9999-12-31 | t
   2 | C2 | Ben Odé   | York  | Trade   | 1900-01-01 | 9999-12-31 | t
   4 | C3 | Cai Lee   | Bath  | Retail  | 1900-01-01 | 9999-12-31 | t
(5 rows)

Ana has three versions: Leeds/Retail until 5 March, York/Retail until 9 March, and York/Trade now. Each closed version ends on the date the next one begins. Ben has one version, now spelt "Ben Odé": the correction was a Type 1 change, so it overwrote his row instead of adding one. Cai has one version. The re-run added nothing, because no attribute differed from the snapshot.

05. Step 4: Load the facts with a point-in-time lookup

Facts store the surrogate key of the version that was valid when the event happened. The lookup joins on the natural key and on the half-open interval: ordered_at >= valid_from AND ordered_at < valid_to. Comparing a timestamp with a date treats the date as midnight, so an order at 16:00 on 4 March falls in the version that ends on 5 March. The second query shows, for every order, the key the point-in-time lookup chose and the key a lookup on is_current would have chosen instead.

SQL · fact.sql
CREATE TABLE fact_orders (
  order_id     int PRIMARY KEY,
  customer_key int NOT NULL REFERENCES dim_customer,
  ordered_at   timestamp NOT NULL,
  amount       numeric(8,2) NOT NULL
);
INSERT INTO fact_orders
SELECT o.order_id, d.customer_key, o.ordered_at, o.amount
FROM src_orders o
JOIN dim_customer d
  ON d.customer_id = o.customer_id
 AND o.ordered_at >= d.valid_from
 AND o.ordered_at <  d.valid_to;

SELECT o.order_id, o.ordered_at::date AS ordered, f.customer_key AS pit_key,
       cur.customer_key AS current_key
FROM src_orders o
JOIN fact_orders f USING (order_id)
JOIN dim_customer cur ON cur.customer_id = o.customer_id AND cur.is_current
ORDER BY o.order_id;
Terminal
docker exec -i sql-lab psql -U postgres -d dw -X -q < fact.sql
Expected output
 order_id |  ordered   | pit_key | current_key 
----------+------------+---------+-------------
        1 | 2026-03-02 |       1 |           5
        2 | 2026-03-03 |       2 |           2
        3 | 2026-03-06 |       3 |           5
        4 | 2026-03-07 |       4 |           4
        5 | 2026-03-10 |       5 |           5
        6 | 2026-03-04 |       1 |           5
(6 rows)

Orders 1, 3 and 5 by Ana point to her three different versions. Order 6, the late one, was placed on 4 March, so it gets key 1, Leeds, although it was loaded after Ana moved. A loader that simply took the current row would have filed all four of Ana's orders under key 5, York/Trade. With timely loads, "look up the current row at load time" and "look up the row valid at event time" usually agree; late facts and reloads of history are exactly where they differ, which is why the interval condition belongs in the fact load. Doing the lookup once, at load time, also keeps report queries simple: they join on customer_key alone.

06. Step 5: Report revenue as it was and as it is

The same facts now answer two different questions. "Where did our revenue come from?" groups by the attributes of the version stored on each fact, the city and segment at the time of the order. "How much have our current Trade customers spent with us?" groups by each customer's current attributes, reached through the natural key. Neither is more correct; they are different questions, and the dimension supports both.

SQL · report.sql
SELECT d.city AS city_at_order, d.segment AS segment_at_order,
       sum(f.amount) AS revenue
FROM fact_orders f JOIN dim_customer d USING (customer_key)
GROUP BY 1, 2 ORDER BY 1, 2;

SELECT cur.city AS current_city, cur.segment AS current_segment,
       sum(f.amount) AS revenue
FROM fact_orders f
JOIN dim_customer d   USING (customer_key)
JOIN dim_customer cur ON cur.customer_id = d.customer_id AND cur.is_current
GROUP BY 1, 2 ORDER BY 1, 2;
Terminal
docker exec -i sql-lab psql -U postgres -d dw -X -q < report.sql
Expected output
 city_at_order | segment_at_order | revenue 
---------------+------------------+---------
 Bath          | Retail           |   20.00
 Leeds         | Retail           |   90.00
 York          | Retail           |   30.00
 York          | Trade            |  150.00
(4 rows)

 current_city | current_segment | revenue 
--------------+-----------------+---------
 Bath         | Retail          |   20.00
 York         | Trade           |  270.00
(2 rows)

As it was: Leeds/Retail earned 90 (orders 1 and 6), York/Retail 30 and York/Trade 150 (Ben's 80 and Ana's 70). As it is: all 270 that Ana and Ben spent shows under York/Trade, because both are York/Trade customers today. Both reports total 290.

07. Step 6: Test the dimension

A Type 2 dimension has rules that SQL constraints alone do not enforce, so test them after every load. Each check below counts problems and should return 0: every customer has exactly one current version; each version starts exactly where the previous one ended, with no gap and no overlap (lag reads the previous version's end); and every source order found a version.

SQL · test.sql
SELECT 'customers without exactly one current row' AS check_name,
       count(*) AS problems
FROM (SELECT customer_id FROM dim_customer
      GROUP BY customer_id HAVING count(*) FILTER (WHERE is_current) <> 1) x
UNION ALL
SELECT 'versions that do not start where the last one ended', count(*)
FROM (SELECT valid_from, lag(valid_to) OVER (PARTITION BY customer_id
                                             ORDER BY valid_from) AS prev_to
      FROM dim_customer) v
WHERE prev_to IS NOT NULL AND prev_to <> valid_from
UNION ALL
SELECT 'source orders missing from the fact', count(*)
FROM src_orders o LEFT JOIN fact_orders f USING (order_id)
WHERE f.order_id IS NULL;
Terminal
docker exec -i sql-lab psql -U postgres -d dw -X -q < test.sql
Expected output
                     check_name                      | problems 
-----------------------------------------------------+----------
 customers without exactly one current row           |        0
 versions that do not start where the last one ended |        0
 source orders missing from the fact                 |        0
(3 rows)

All three checks pass. To see one fail, run UPDATE dim_customer SET valid_to = '2026-03-04' WHERE customer_key = 1; and run the tests again: the gap check reports one problem, and order 6 would no longer find a version if you reloaded the facts. Reload from step 1 to restore the data.

08. Check your understanding

Practice check · 3 questions

Versions, lookups and tests

These questions change one detail of the lab. Pick the best answer.

Q1. A loader picks `customer_key` with `WHERE is_current`. On 20 May it loads an order placed on 10 May; the customer changed segment on 15 May. Which version does the fact get?
Q2. Without the partial unique index, a test finds a customer with two rows where `is_current` is true. Which loader bug is the most likely cause?
Q3. Daily snapshots show a customer in segment A on day 1, B on day 2 and A again on day 3, with city and segment as Type 2 attributes. After the three loads, how many versions does the customer have?
Practice only: not graded, not saved, not evidence.

09. Apply it

The practice project asks you to implement the plan dimension of a subscription business as SCD Type 2 and to report revenue by the plan that was valid at payment time. Use this lab as the template:

  1. Decide, attribute by attribute, which plan attributes are Type 1 (a corrected description) and which are Type 2 (price, billing period).
  2. Write load_dim_plan(p_date) with the same three statements and a partial unique index.
  3. Load payments with a point-in-time lookup, including one late payment, and write the "as it was" revenue query.
  4. Add the three tests, and a fourth of your own: no version may have valid_to <= valid_from.
  5. Decide what your loader should do when a customer disappears from a snapshot, and document it.

10. Review prompt

Without looking back, explain:

  • the difference between Type 1 and Type 2, with one attribute that suits each;
  • why a Type 2 dimension needs a surrogate key, and why its validity interval is half-open;
  • the three statements of the loader, and why their order matters;
  • how a point-in-time lookup chooses the version for a fact, and when it gives a different answer from an is_current lookup;
  • the difference between the "as it was" and "as it is" reports.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check