How to Implement Slowly Changing Dimensions
Model changing attributes over time: compare Type 1, Type 2, and Type 4 history, write Type 2 rows with validity ranges, and query as of a date.
On this page
Introduction
An entity’s attributes change over time: a customer moves, a product’s price changes, a plan is upgraded. If you overwrite the old value, you lose the ability to answer questions about the past, such as how much revenue came from customers on the premium plan last quarter. Slowly changing dimensions are the patterns for keeping attribute history, and choosing the wrong one either discards data you need or stores history you never use.
This tutorial compares the common approaches, focuses on the Type 2 pattern that keeps a version row per change with validity ranges, shows how to write changes transactionally so no gap or overlap appears, and how to query the state as of a past date. The examples use PostgreSQL range types and constraints, but the modeling reasoning is general.
Compare the history strategies
Type 1 overwrites the attribute with the new value and keeps no history. It is correct when only the current value matters, and it is the cheapest. Type 2 inserts a new row for each change, creating a version chain, which preserves full history and lets you reconstruct any past state. Type 4 splits rapidly changing attributes into a separate history table, keeping the main dimension small. A common hybrid keeps the current value on the main row for fast joins and the full history in a companion table.
Choose from the questions you must answer. If an audit or a report needs the value as of a past event, you need history, which points to Type 2 or Type 4. If you only ever join to the current value, Type 1 is simpler and avoids the cost of chaining. Decide per attribute, because a dimension can mix strategies: name might be Type 2 for audit while a rarely read description is Type 1.
-- Type 2 dimension with validity range and a current flag
CREATE TABLE customer_dim (
customer_id bigint NOT NULL,
version int NOT NULL,
plan text NOT NULL,
valid_from timestamptz NOT NULL,
valid_to timestamptz NOT NULL DEFAULT 'infinity',
is_current boolean NOT NULL GENERATED ALWAYS AS (valid_to = 'infinity') STORED,
PRIMARY KEY (customer_id, version)
);
Store and enforce validity ranges
A Type 2 row spans a validity range: valid_from is when the version took effect and valid_to is when it ended, left open for the current version. Exactly one row per entity should be open at any instant, and the open rows must not overlap. Enforce this in the schema so a buggy writer cannot create two overlapping versions.
PostgreSQL can enforce non-overlap with an exclusion constraint over a range type, preventing two versions of the same entity from having overlapping valid ranges. Alternatively, a partial unique index on the entity where the row is current allows only one current row per entity. Use the exclusion constraint when you need to forbid overlap generally, and the partial unique index when the simpler invariant one-open-row is enough.
-- at most one open version per customer
CREATE UNIQUE INDEX one_current_per_customer
ON customer_dim (customer_id)
WHERE valid_to = 'infinity';
-- or forbid any overlap using a range type and an exclusion constraint
ALTER TABLE customer_dim ADD COLUMN valid tstzrange
GENERATED ALWAYS AS (tstzrange(valid_from, valid_to, '[)')) STORED;
ALTER TABLE customer_dim ADD CONSTRAINT no_overlap
EXCLUDE USING gist (customer_id WITH =, valid WITH &&);
Write versions transactionally
A change is two writes that must succeed or fail together: close the current row by setting its valid_to, and insert the new row with valid_from equal to that same instant. Do both in one transaction so a crash between them cannot leave the entity with no current row or with an overlap. Never close and open in separate transactions or with different timestamps, or a gap or overlap appears.
Make the write idempotent-friendly by keying it on the entity and using the same timestamp for the close and the open. If two changes arrive close together, serialize them per entity with a row lock so the second sees the row the first closed. Wrap the close-and-open in a function so every caller uses the same logic, and test it under concurrent changes to the same entity.
-- close current, insert new, in one transaction
BEGIN;
UPDATE customer_dim
SET valid_to = $2
WHERE customer_id = $1 AND valid_to = 'infinity';
INSERT INTO customer_dim (customer_id, version, plan, valid_from)
VALUES ($1, (SELECT coalesce(max(version),0)+1 FROM customer_dim WHERE customer_id=$1), $3, $2);
COMMIT;
Query the state as of a date
With validity ranges, reconstructing the past is a range filter. To find the plan a customer had on a given date, select the version whose range contains that date. With a range type, the containment operator makes this a single predicate; with separate columns, valid_from <= t AND valid_to > t. Join events to the dimension on the event timestamp so each fact is enriched with the attribute value that was true when it happened.
Index the range or the pair of valid_from and valid_to so the as-of join seeks rather than scans. This as-of join is the reason Type 2 exists: it lets a report join a fact table to the dimension version that was current at the fact’s time, producing historically accurate results instead of today’s values applied to the past.
SELECT e.id, e.amount, d.plan
FROM events e
JOIN customer_dim d
ON d.customer_id = e.customer_id
AND d.valid @> e.created_at -- the version valid at the event time
WHERE e.created_at >= '2026-01-01';
Test the history and boundaries
Test that after two changes there are exactly two versions with the first closed. Test the boundary dates: the instant a version takes effect belongs to the new version, not the old, and an as-of query at that instant returns the new value. Test that concurrent changes to the same entity cannot create two open rows, which the unique index should reject. These tests prove both the history and the integrity constraints.
psql -d app <<'SQL'
-- after a change, the old version must be closed
SELECT count(*) FROM customer_dim WHERE customer_id = 1 AND valid_to = 'infinity'; -- expect 1
-- as-of query at the exact change instant returns the new plan
SELECT plan FROM customer_dim WHERE customer_id = 1 AND valid @> '2026-03-01 00:00:00+00';
SQL
Common pitfalls
Overwriting a value that a past report needed, closing and opening a version in separate transactions so a gap or overlap appears, using different timestamps for the close and the open, allowing two current rows per entity, and forgetting to join facts on the event time so reports use today’s values are the recurring mistakes. Transactional close-and-open, validity constraints, and as-of joins address them.
Conclusion
Slowly changing dimensions are about answering questions about the past. Use Type 1 when only the current value matters and Type 2 when you must reconstruct history, store validity ranges with a constraint that forbids overlap, write the close and open in one transaction, and join facts on the event time for historical accuracy. Self-check by asserting one open row per entity and an as-of query at the change boundary. Then a report reflects what was true, not just what is true now.
Sources: Kimball: Slowly changing dimensions, PostgreSQL: Range types and exclusion constraints, PostgreSQL: EXCLUDE constraints.
FAQ
- When do I need Type 2 history?
- When a report, an audit, or a calculation must use the attribute value that was true at the time of a past event, not the current value. If you only ever need the latest value, Type 1 overwrite is simpler and cheaper.
- How do I avoid overlapping validity ranges?
- Write each change in one transaction that closes the current row and opens the new one, and add a check constraint or an exclusion constraint that rejects overlap and multiple open rows per entity.
Report a problem with this articleOpens a pre-filled issue on GitHub.