Top-N Reports in SQL
'Show me the top 5' is the most common report there is: aggregate, sort, then LIMIT.
Top-N questions are common in dashboards: the best-selling products, the busiest customers, the slowest orders. A common pattern is to aggregate to get a number per group, sort by it, then LIMIT to the few rows you care about.
Here "revenue" is
sum(quantity * unit_price)
across a product's line items. The starter already builds the full ranked
list. Your job is to keep only the top five.
select category, sum(amount) as total
from sales
group by category
order by total desc
limit 10 Preparing for an interview? The ranking and top-N interview questions add ties and top-N per group, with model answers to compare against.
Schema · Garden Shop Tables · order_items, products 2 tables
One row per line item within an order.
One row per product, with price, cost, and inventory levels.
Find the top 5 products by total revenue. Return
product_name and revenue, biggest first.
Run your query to inspect the result.
Expected answer
- Columns: product_name, revenue.
- Rows: the top 5 products by revenue.
- Revenue multiplies quantity by unit_price across every line item for that product.
Related
Nested SELECTs, IN, EXISTS, and correlation.
Ranking, LAG/LEAD, and running totals at a glance.
Practice ranking, running totals, and top row per group.
The default RANGE frame groups tied rows; use ROWS.
Filter window results in a CTE or with QUALIFY.
The WITH clause, chained steps, and CTE vs subquery.