23. Previous order without a self-join Solved
PerformanceHardwindow vs self-joinLAGquery plan
For every order return id, customer_id, placed_at and days_since_previous: whole days since that customer's previous order (by placed_at, then id; NULL for their first). Sort by customer_id, placed_at, id. Constraint: no join at all. The plan must read orders once and use a window.
Your answer returns 300 rows with the columns id, customer_id, placed_at, days_since_previous. 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
lag(placed_at) OVER (PARTITION BY customer_id ORDER BY placed_at, id); date_diff('day', prev, placed_at).Common traps
- A self-join on "the latest earlier order" is quadratic per customer.
Solution
SELECT id, customer_id, placed_at,
date_diff('day', lag(placed_at) OVER (PARTITION BY customer_id ORDER BY placed_at, id), placed_at) AS days_since_previous
FROM orders
ORDER BY customer_id, placed_at, id
Why it is fast
The slower version returns exactly the same rows:
SELECT o.id, o.customer_id, o.placed_at,
date_diff('day', (SELECT max(p.placed_at) FROM orders p
WHERE p.customer_id = o.customer_id
AND (p.placed_at < o.placed_at OR (p.placed_at = o.placed_at AND p.id < o.id))), o.placed_at) AS days_since_previous
FROM orders o
ORDER BY o.customer_id, o.placed_at, o.id
How this is graded: on DuckDB's physical plan of your final statement (EXPLAIN (FORMAT JSON)): no join operator; orders is scanned at most once; the plan contains WINDOW.
Free for personal practice. Please don't republish the questions or solutions. See the Playground License Terms.