Slowly Changing Dimension Write In One CTE
Close the previous version row and insert the replacement in one data-modifying CTE so slowly changing dimension history keeps a single open row.
Code
-- An SCD2 (slowly changing dimension) table keeps history: valid_to NULL marks the currently open row
CREATE TABLE dim_price (
sku text NOT NULL,
price_cents int NOT NULL,
valid_from date NOT NULL,
valid_to date, -- NULL = still open
PRIMARY KEY (sku, valid_from)
);
INSERT INTO dim_price (sku, price_cents, valid_from)
VALUES ('A-1', 1999, DATE '2026-01-01');
-- Closing the old version and inserting the new one happen in one data-modifying CTE:
-- The WITH clause INSERTs the new row and RETURNs its start date; the outer UPDATE closes the previously open row
WITH new_version AS (
INSERT INTO dim_price (sku, price_cents, valid_from)
VALUES ('A-1', 2499, DATE '2026-03-01')
RETURNING sku, valid_from
)
UPDATE dim_price AS old_row
SET valid_to = new_version.valid_from - 1
FROM new_version
WHERE old_row.sku = new_version.sku
AND old_row.valid_from < new_version.valid_from
AND old_row.valid_to IS NULL;
SELECT sku, price_cents, valid_from, valid_to FROM dim_price ORDER BY valid_from;How it works
The file runs SELECT / INSERT / UPDATE / CREATE statements, touching the table dim_price (through the new_version CTE result set).
What the statements actually assemble: a CTE (WITH … AS) that names an intermediate result before the main query; a WHERE clause narrowing which rows one statement affects; an ORDER BY that fixes the output order; a RETURNING clause that hands the affected rows back to the caller; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.
Applying it
The dim_price table is the working surface here.
Statements that matter
CREATE TABLE dim_price (
sku text NOT NULL,
price_cents int NOT NULL,
valid_from date NOT NULL,
valid_to date, -- NULL = still open
PRIMARY KEY (sku, valid_from)
);
INSERT INTO dim_price (sku, price_cents, valid_from)
VALUES ('A-1', 1999, DATE '2026-01-01');
SELECT sku, price_cents, valid_from, valid_to FROM dim_price ORDER BY valid_from;
Interactive Tools for This Topic
FAQ
- Name the tables involved in this file.
- The references are `dim_price`, `new_version`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.