Lompat ke konten

Pelajaran 14 ยท History and Slowly Changing Dimensions

SCD Type 2 in SQL

Implement SCD Type 2 in SQL step by step: detect changes, close old versions, insert new ones, run point-in-time joins and test for overlaps and gaps.

In a Type 2 dimension, every version of a record is its own row with a validity period. This lesson builds the load that maintains those rows, then shows how to use and test them.

The columns

Column Purpose
customer_key Surrogate key, different for each version
customer_id Natural key, the same for all versions
attributes The tracked values
valid_from First date this version applies
valid_to Date it stops applying
is_current A convenient flag for the latest version

Use half-open periods: a version is valid when date >= valid_from AND date < valid_to. The old row's valid_to equals the new row's valid_from, so there are no gaps and no overlaps, even with timestamps. For the current row, many teams store a far-future date such as 9999-12-31, which keeps join conditions simple. Others use NULL; choose one convention.

The load in two steps

Each run compares incoming data with current rows:

  1. Close current rows whose tracked attributes changed.
  2. Insert a new version for changed records, and a first version for new records.

After step 1, a changed customer has no current row, just like a new customer. So step 2 is one simple rule: insert every incoming record that has no current row.

SQL A two-step Type 2 load

Press Run (or Ctrl + Enter) to see the result here.

Run it in your head again with the same staging data: step 1 finds no differences, and step 2 finds a current row for everyone. Rerunning changes nothing. That property, called idempotence, matters whenever a job is retried.

Three details:

  • Comparing with <> would miss a change from NULL to a value, because the result is unknown. SQLite offers IS NOT. Standard SQL has IS DISTINCT FROM; check what your platform supports.
  • Run both steps in one transaction, so readers never see a customer with no current row.
  • This code treats a missing record as "no change". Whether absence means deletion depends on whether the source sends a full snapshot or only changes. Handle deletions explicitly.

The load date 2026-03-01 is typed in for clarity. A real job receives it as a parameter. Prefer the date the change took effect in the source, if the source provides it, over the date you happened to load it.

Platform syntax

Many platforms offer MERGE to combine updates and inserts. Because a single source row must both close the old version and insert a new one, a Type 2 load with MERGE usually needs a follow-up INSERT or a specially prepared source. Some tools also automate Type 2; for example, dbt calls the feature snapshots.

Point-in-time joins

When you load a fact, find the version that was valid on the event date, and store its surrogate key.

SQL Look up the right version for each sale

Press Run (or Ctrl + Enter) to see the result here.

S2 matches only the Bogota version because of the half-open rule. With BETWEEN, which includes both ends, it would match two versions and duplicate the sale.

Test the history

SQL Detect broken histories

Press Run (or Ctrl + Enter) to see the result here.

The first query reports an overlap for B and C and a gap for D. The second reports C, which has two current rows. A gap can be intentional, for instance if a record was deleted and later restored, so confirm your rule. Run checks like these after every load.

For more on this pattern, see slowly changing dimensions in data engineering.

More than one change between loads

A snapshot shows the state at the moment it is taken. If a customer moved twice between two nightly runs, you see only the last city. The history in your dimension is then the history of observed states. When every intermediate change matters, you need a change feed or an audit table from the source, and you apply the changes in order.

Also decide what happens when two changes share the same effective date. With date-level periods, closing and opening on the same day creates a version where valid_from equals valid_to. Under the half-open rule it matches no date. You can use timestamps instead, or keep only the last state for each day. Choose deliberately.

Detecting changes in many columns

Comparing twenty columns one by one is tedious and easy to get wrong. A common technique stores a change hash: a hash of all tracked attributes in a fixed order and format. The load compares one value. The same cautions as for hashed keys apply: represent NULL differently from an empty string, put a separator between parts and format dates and numbers consistently. When you add a tracked column, the hashes of old rows must be recalculated in a controlled way, or every record will appear to have changed.

Rebuilding history

If you retain all raw snapshots, you can rebuild the dimension after fixing a bug by replaying them in order. Rebuilding assigns new keys unless your key method reproduces the old ones, and facts store those keys. Plan to either preserve keys or reload the affected facts in the same release.

Keep the dimension readable

Many versions make a dimension harder to explore. Publish a view of current rows for people who only need the latest state, and keep the full table for historical joins.

Common mistakes

Do not include volatile technical columns, such as the extract timestamp, in the change comparison. Every load would then create a new version for every record.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. With half-open periods, which condition finds the version valid on a date d?

    Including the start and excluding the end gives exactly one match at a changeover.
  2. 2. Why does the change test need a NULL-safe comparison?

    Ordinary inequality with NULL yields unknown, which a WHERE clause treats as not matched.
  3. 3. What does it mean that this load is idempotent?

    Retries do not create duplicate versions.
  4. 4. Which surrogate key should a late-loaded sale from February store?

    A point-in-time lookup uses the event date, not the load date.

Summary

  • Type 2 rows carry a natural key, a surrogate key and a validity period.
  • Close changed current rows, then insert rows for anything without a current version.
  • Use NULL-safe comparisons, one transaction and half-open periods.
  • Join facts by event date and test for overlaps, gaps and duplicate current rows.

Next: ETL and ELT

Progres Anda disimpan di browser ini. Tidak perlu akun.