24. Latest order per customer Solved
PerformanceHardQUALIFYarg_maxgreatest-n-per-group
For each customer return customer_id, name, and their latest order's order_id, placed_at and status (latest by placed_at, then highest id). Sort by customer_id. Constraint: read orders only once (no join of orders to an aggregate of orders).
Your answer returns 20 rows with the columns customer_id, name, order_id, placed_at, status. 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
QUALIFY row_number() OVER (PARTITION BY customer_id ORDER BY placed_at DESC, id DESC) = 1, or arg_max.Common traps
- Joining orders to
SELECT customer_id, max(placed_at) …reads orders twice and returns duplicates on ties.
Solution
SELECT c.id AS customer_id, c.name, o.id AS order_id, o.placed_at, o.status
FROM orders o
JOIN customers c ON c.id = o.customer_id
QUALIFY row_number() OVER (PARTITION BY o.customer_id ORDER BY o.placed_at DESC, o.id DESC) = 1
ORDER BY customer_id
Why it is fast
The slower version returns exactly the same rows:
SELECT c.id AS customer_id, c.name, o.id AS order_id, o.placed_at, o.status
FROM orders o
JOIN (SELECT customer_id, max(placed_at) AS last_at FROM orders GROUP BY customer_id) m
ON m.customer_id = o.customer_id AND m.last_at = o.placed_at
JOIN customers c ON c.id = o.customer_id
WHERE o.id = (SELECT max(id) FROM orders x WHERE x.customer_id = o.customer_id AND x.placed_at = m.last_at)
ORDER BY customer_id
How this is graded: on DuckDB's physical plan of your final statement (EXPLAIN (FORMAT JSON)): orders is scanned at most once.
Free for personal practice. Please don't republish the questions or solutions. See the Playground License Terms.