Full answer
Schema sketch (illustrative, not run here):
sql
CREATE TABLE product_prices (
product_id bigint NOT NULL,
price numeric(12,2) NOT NULL,
valid tstzrange NOT NULL,
changed_by text,
EXCLUDE USING gist (product_id WITH =, valid WITH &&)
);
-- price as of a moment
SELECT price FROM product_prices WHERE product_id = $1 AND valid @> $2::timestamptz;
-- current prices
CREATE INDEX ON product_prices (product_id) WHERE upper_inf(valid);Design points:
- Changing a price is one transaction that closes the current row (set the upper bound to now) and inserts the new row starting at the same instant; the exclusion constraint guarantees no gaps are filled twice, and a check that bounds are half-open avoids double counting at the boundary.
- Use timestamptz ranges for prices that change within a day.
- Joins from orders to the price in effect at order time use the same @> condition, or store the price on the order line, which is usually the right choice for invoices.
- Corrections to the past (bitemporal needs) require a second time dimension, recorded_at, if the business must know what was believed at a given time.
- For audits of every column of many tables, a generic audit log table or trigger-based history may be simpler than temporal modelling per table.
Key points
- One row per version with a validity range
- Exclusion constraint prevents overlaps
- GiST index serves as-of queries
- Close and open versions in one transaction
- Bitemporal needs a second time axis
Common mistakes
- Overwriting prices and losing history
- Inclusive end dates causing double matches
Follow-ups
- How would you query price changes during a month?
- When is a bitemporal model necessary?
Tips
- Use half-open ranges