Ranking window functions
SQL · 16 questions
Short notes
Key idea
Window functions compute a value for each row using a group of related rows, without collapsing them like GROUP BY does. Ranking is the most common use.
Syntax
ROW_NUMBER() OVER (PARTITION BY city ORDER BY amount DESC)
RANK() OVER (ORDER BY score DESC)
DENSE_RANK() OVER (ORDER BY score DESC)
For scores 90, 90, 80: ROW_NUMBER gives 1, 2, 3; RANK 1, 1, 3; DENSE_RANK 1, 1, 2.
Example
Top 2 orders in each city:
WITH ranked AS (
SELECT city, order_id, amount,
ROW_NUMBER() OVER (PARTITION BY city ORDER BY amount DESC) AS rn
FROM orders
)
SELECT * FROM ranked WHERE rn <= 2;
Traps
- You can't filter a window function in
WHEREof the same query; wrap it in a CTE first (DuckDB also hasQUALIFY, but most databases don't). PARTITION BYrestarts the numbering per group; leaving it out ranks the whole table.- Pick the function by how you want ties: "the 2nd highest salary" usually wants
DENSE_RANK.
Want the full lesson with step-by-step examples, a project and a certificate? SQL course, ₹120 →
- Question 1easy
Scores are 100, 90, 90, 80, highest first. What does
DENSE_RANK()give the 80? - Question 2medium
Why does
SELECT ..., ROW_NUMBER() OVER (...) AS rn FROM products WHERE rn = 1fail? - Question 3hard
In
order_items, 42 lines have quantity 5 (the highest), 16 have quantity 3, 43 have quantity 2, and 65 have quantity 1. What does this return?SELECT COUNT(*) FROM ( SELECT RANK() OVER (ORDER BY quantity DESC) AS r FROM order_items ) WHERE r <= 2;
- Question 4hard
Same data as before. What does this return?
SELECT COUNT(*) FROM ( SELECT DENSE_RANK() OVER (ORDER BY quantity DESC) AS r FROM order_items ) WHERE r <= 2;
- Question 5medium
Products have 5 named categories, and 2 products have no category. What does this return?
SELECT COUNT(*) FROM ( SELECT ROW_NUMBER() OVER (PARTITION BY category ORDER BY price DESC) AS rn FROM products ) WHERE rn = 1;
Ranking window functions
Ranking window functions
Ranking window functions
Ranking window functions
Ranking window functions
11 more questions on this topic, with hints, and tests
Sign up free for 21 days of every question and test.