Temporal joins
Overview
An as-of join matches a fact to the dimension version valid at the fact time, not the current version. Join by business key and temporal containment. This is useful for historical pricing or organizational reporting.
First example
SELECT s.id,s.day,r.price FROM tm_sale s LEFT JOIN tm_rate r ON r.product_id=s.product_id AND r.start_day<=s.day AND s.day<r.end_day ORDER BY s.id;Observed SQLite result (rows in JSON):
[ [ 1, 4, 100 ], [ 2, 5, 120 ], [ 3, 10, null ]]How it works
Place the validity predicates inside ON for a LEFT JOIN, so facts without a matching rate survive with NULL prices. The first query matches sales on days 4 and 5 to different rates. The second calculates intersections of nonempty bounded intervals using max(start) and min(end) after the overlap filter; SQLite scalar max/min correspond to PostgreSQL GREATEST/LEAST here. Overlapping dimension versions can multiply fact rows, so enforce nonoverlap and check gaps explicitly.
Practical example
SELECT r.id,max(r.start_day,3),min(r.end_day,7) FROM tm_rate r WHERE r.product_id=1 AND r.start_day<7 AND 3<r.end_day ORDER BY r.id;Observed SQLite result (rows in JSON):
[ [ 1, 3, 5 ], [ 2, 5, 7 ]]Practice and mistakes
Practice: list sales with no historical rate. Hint 1: use LEFT JOIN and put time predicates in ON. Hint 2: filter WHERE r.id IS NULL after the join. Sale 3 has no rate. A missing historical rate is not automatically zero.
PostgreSQL 17 example — NOT RUN
WITH rates(id,span) AS (VALUES (1,int4range(1,5)),(2,int4range(5,10)))SELECT id,(span * int4range(3,7))::text FROM rates WHERE span && int4range(3,7) ORDER BY id;Expected result, not executed: [[1, "[3,5)"], [2, "[5,7)"]]