Video in progress

How do you design the schema to keep product price history and answer the question "what was the price on March 15?"?

I store the price in a separate history table with a validity range: valid_during tstzrange. An exclusion constraint guarantees that ranges don't overlap, and a GiST index makes the "price at that time" query fast. I keep the current price in a separate column or fetch it with an upper_inf condition.

📖 Answer

If we just update the product.price column, the old price is lost and an old order can't be recalculated. You also need to copy the price onto the order, but for reports like "how did the price change last month" the history has to live separately.

CREATE EXTENSION IF NOT EXISTS btree_gist;

CREATE TABLE product_price (
    product_id   bigint        NOT NULL REFERENCES product(id),
    price        numeric(12,2) NOT NULL,
    valid_during tstzrange     NOT NULL,
    EXCLUDE USING gist (product_id WITH =, valid_during WITH &&)
);

Changing the price means closing the old range and opening a new one in one transaction:

UPDATE product_price
SET    valid_during = tstzrange(lower(valid_during), :now)
WHERE  product_id = :id AND upper_inf(valid_during);

INSERT INTO product_price VALUES (:id, :price, tstzrange(:now, NULL));

The price at a given time:

SELECT price FROM product_price
WHERE product_id = :id AND valid_during @> '2026-03-15 12:00+05'::timestamptz;

Two parallel changes can't corrupt each other: if the ranges overlap, the exclusion constraint rejects the second one.

An alternative is a plain valid_from column and a "latest valid_from <= t" query. It's simple, but the database doesn't guarantee that the ranges don't overlap. PG18 also added a temporal primary key with WITHOUT OVERLAPS, but I still prefer working with an exclusion constraint, since it exists in more versions.