← Back to PostgreSQL, page 5

postgresql-0100 · Hard senior

Design a schema to store the full history of price changes so that 'price as of any date' queries are fast and correct.

Store one row per price version with a validity period, either valid_from and valid_to columns or a daterange or tstzrange, and enforce no overlaps per product with an exclusion constraint. 'As of' queries then filter on period @> the date, served by a GiST index. Keep current prices queryable cheaply, for example with a partial index on open-ended rows or a separate current table.

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