View a markdown version of this page

ASOF joins - Amazon Athena

ASOF joins

An ASOF join matches each row of the left source with at most one row of the right source. Of the rows that meet the condition, it picks the one closest to the left row. The condition has equality comparisons, such as t.symbol = p.symbol, and exactly one inequality, such as t.trade_time >= p.price_time. With >=, the match is the latest right row at or before the left row.

An ASOF JOIN leaves out left rows that have no match. An ASOF LEFT JOIN keeps them, with NULL in the columns of the right source.

Syntax

from_item ASOF [ LEFT ] JOIN from_item ON [ equality_condition AND [ ... ] ] inequality_condition

Examples

The following SQL query finds, for each trade, the latest price of the same symbol at or before the time of the trade.

SELECT t.symbol, t.trade_time, p.price FROM (VALUES ('AAA', TIMESTAMP '2026-10-01 10:05:00'), ('AAA', TIMESTAMP '2026-10-01 10:15:00'), ('BBB', TIMESTAMP '2026-10-01 10:15:00') ) AS t(symbol, trade_time) ASOF JOIN (VALUES ('AAA', TIMESTAMP '2026-10-01 10:00:00', 100.0), ('AAA', TIMESTAMP '2026-10-01 10:10:00', 101.5), ('BBB', TIMESTAMP '2026-10-01 10:00:00', 20.0) ) AS p(symbol, price_time, price) ON t.symbol = p.symbol AND t.trade_time >= p.price_time ORDER BY t.symbol, t.trade_time

The query returns the following results.

symbol trade_time price

AAA

2026-10-01 10:05:00

100.0

AAA

2026-10-01 10:15:00

101.5

BBB

2026-10-01 10:15:00

20.0

The following SQL query uses ASOF LEFT JOIN, so it keeps the trade at 09:55, which comes before the first price, with a NULL price.

SELECT t.trade_time, p.price FROM (VALUES (TIMESTAMP '2026-10-01 09:55:00'), (TIMESTAMP '2026-10-01 10:05:00') ) AS t(trade_time) ASOF LEFT JOIN (VALUES (TIMESTAMP '2026-10-01 10:00:00', 100.0) ) AS p(price_time, price) ON t.trade_time >= p.price_time ORDER BY t.trade_time

The query returns the following results.

trade_time price

2026-10-01 09:55:00

NULL

2026-10-01 10:05:00

100.0