29. Ten slowest page loads Solved
PerformanceMediumTop-NORDER BY + LIMITquery plan
Return the 10 slowest page_view events: event_id, ts, path (from page.path) and load_ms. Sort by load_ms descending, then event_id. Constraint: the plan must use DuckDB's Top-N operator, which keeps only the best 10 rows while scanning instead of sorting everything.
Your answer returns 10 rows with the columns event_id, ts, path, load_ms. 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
ORDER BY … LIMIT 10 becomes a TOP_N operator.Common traps
row_number() OVER (ORDER BY load_ms DESC) <= 10sorts all 10,000 views first.
Solution
SELECT event_id, ts, page.path AS path, load_ms
FROM web_events
WHERE event_type = 'page_view'
ORDER BY load_ms DESC, event_id
LIMIT 10
Why it is fast
The slower version returns exactly the same rows:
SELECT event_id, ts, path, load_ms FROM (
SELECT event_id, ts, page.path AS path, load_ms,
row_number() OVER (ORDER BY load_ms DESC, event_id) AS rn
FROM web_events WHERE event_type = 'page_view'
) WHERE rn <= 10
ORDER BY load_ms DESC, event_id
How this is graded: on DuckDB's physical plan of your final statement (EXPLAIN (FORMAT JSON)): the plan contains TOP_N; the plan contains no WINDOW.
Free for personal practice. Please don't republish the questions or solutions. See the Playground License Terms.