30. ASOF JOIN instead of a correlated lookup Solved
PerformanceExpertASOF JOINcorrelated subqueriesquery plan
For every GBP order placed in January 2024, return order_id, placed_at and rate: the GBP per_eur rate valid when it was placed (latest valid_from at or before placed_at). Sort by placed_at, then order_id. Constraint: the plan must use an ASOF join, not a correlated "latest earlier rate" subquery.
Your answer returns 6 rows with the columns order_id, placed_at, rate. Order matters.
The data
The store from the DuckDB playground, running in your browser with DuckDB. Prices are in EUR; the data covers 2024.
customers20 rows
id | INTEGER primary key |
name | VARCHAR |
country | VARCHAR |
currency | VARCHAR EUR, GBP, USD or JPY |
signed_up | DATE |
tags | VARCHAR[] a list: vip, newsletter, b2b, returns-often |
products10 rows
id | INTEGER primary key |
name | VARCHAR |
category | VARCHAR |
price | DECIMAL(10,2) EUR |
specs | STRUCT weight_g INTEGER, color VARCHAR, sizes VARCHAR[] |
orders300 rows
id | INTEGER primary key |
customer_id | INTEGER → customers.id |
placed_at | TIMESTAMP 2024 |
status | ENUM placed, paid, shipped, delivered, returned |
currency | VARCHAR the customer's currency |
order_items576 rows
order_id | INTEGER → orders.id |
product_id | INTEGER → products.id |
quantity | INTEGER |
unit_price | DECIMAL(10,2) EUR |
web_events20,000 rows
event_id | BIGINT |
ts | TIMESTAMP |
session_id | VARCHAR |
customer_id | INTEGER NULL for anonymous visitors |
event_type | VARCHAR page_view, search, add_to_cart, checkout |
page | STRUCT path, referrer |
device | STRUCT browser, mobile BOOLEAN, screen STRUCT(w, h) |
product_ids | INTEGER[] |
load_ms | INTEGER |
fx_rates720 rows
currency | VARCHAR USD, GBP, JPY |
valid_from | TIMESTAMP |
per_eur | DOUBLE units of currency per 1 EUR |
Hints
FROM orders o ASOF JOIN fx_rates fx ON fx.currency = o.currency AND fx.valid_from <= o.placed_at.Common traps
(SELECT per_eur … ORDER BY valid_from DESC LIMIT 1)per order is a nested lookup for every row.
Solution
SELECT o.id AS order_id, o.placed_at, fx.per_eur AS rate
FROM orders o
ASOF JOIN fx_rates fx ON fx.currency = o.currency AND fx.valid_from <= o.placed_at
WHERE o.currency = 'GBP' AND o.placed_at >= TIMESTAMP '2024-01-01' AND o.placed_at < TIMESTAMP '2024-02-01'
ORDER BY o.placed_at, order_id
Why it is fast
The slower version returns exactly the same rows:
SELECT o.id AS order_id, o.placed_at,
(SELECT fx.per_eur FROM fx_rates fx
WHERE fx.currency = o.currency AND fx.valid_from <= o.placed_at
ORDER BY fx.valid_from DESC LIMIT 1) AS rate
FROM orders o
WHERE o.currency = 'GBP' AND o.placed_at >= TIMESTAMP '2024-01-01' AND o.placed_at < TIMESTAMP '2024-02-01'
ORDER BY o.placed_at, order_id
How this is graded: on DuckDB's physical plan of your final statement (EXPLAIN (FORMAT JSON)): the plan contains ASOF_JOIN.
Free for personal practice. Please don't republish the questions or solutions. See the Playground License Terms.