What is an as-of or nearest-match join, and how would you implement it in SQL for aligning time-series data?
Last updated
An as-of join matches each row to the single closest row in another table by time (usually the latest at or before its timestamp), e.g. aligning trades to quotes.
Some engines support it natively (DuckDB
ASOF JOIN, ClickHouseASOF LEFT JOIN). Portably, use aLATERALsubquery withts <= t.ts ORDER BY ts DESC LIMIT 1or keepROW_NUMBER()rank 1.Match an equality key (e.g.
symbol) first so the time search stays within one entity for correctness and speed.