How to Use CTEs and Window Functions in Analytical SQL
How do you get the top N rows per group in SQL?
Use a window function inside a CTE: rank rows within each group with ROW_NUMBER() OVER (PARTITION BY group ORDER BY metric DESC), then filter rank <= N in the outer query. You can't filter a window function in the same query's WHERE clause. Use RANK or DENSE_RANK instead of ROW_NUMBER if tied rows should all be included.
Top 3 products by revenue in each region
WITH product_revenue AS (
SELECT s.region,
s.product_id,
SUM(s.amount) AS revenue
FROM sales s
WHERE s.sale_date >= DATE '2026-10-01'
AND s.sale_date < DATE '2026-11-01'
GROUP BY s.region, s.product_id
),
ranked AS (
SELECT pr.*,
ROW_NUMBER() OVER (PARTITION BY pr.region ORDER BY pr.revenue DESC) AS rn
FROM product_revenue pr
)
SELECT region, product_id, revenue
FROM ranked
WHERE rn <= 3
ORDER BY region, rn;The date filter uses a half-open range (>= start AND < next start). That stays correct when sale_date includes a time, which BETWEEN '2026-10-01' AND '2026-10-31' would miss after midnight on the last day.
ROW_NUMBER vs. RANK vs. DENSE_RANK
- ROW_NUMBER: always 1, 2, 3 — ties are broken arbitrarily unless you add a tie-breaker column. Exactly N rows per group.
- RANK: ties share a rank and the next rank is skipped (1, 1, 3). May return more than N rows.
- DENSE_RANK: ties share a rank with no gaps (1, 1, 2). Use it for “top 3 distinct revenue values.”
Dialect notes
Oracle doesn't support LIMIT. For a simple overall limit in Oracle 12c and later, use FETCH FIRST n ROWS ONLY. PostgreSQL, MySQL, and SQLite use LIMIT. Snowflake, BigQuery, and Databricks also support QUALIFY, which filters a window function directly:
-- Snowflake / BigQuery / Databricks
SELECT region, product_id, revenue
FROM product_revenue
QUALIFY ROW_NUMBER() OVER (PARTITION BY region ORDER BY revenue DESC) <= 3;Common mistakes
- Putting the window function in WHERE — it errors, because window functions are evaluated after WHERE.
- Ranking before aggregating, so you get top order lines instead of top products.
- Using ROW_NUMBER without a tie-breaker and getting different results on each run.
Related skills
Data Analyst Toolkit includes AI-agent skills that follow this method: