SQL ROW_NUMBER, RANK and DENSE_RANK
ROW_NUMBER gives each row a unique number in its partition. RANK gives tied rows the same rank and skips numbers after a tie. DENSE_RANK gives ties the same rank without gaps.
The classic interview question "find the most expensive product in each category" is solved by ranking in a subquery and keeping rank 1.
Syntax
ROW_NUMBER() OVER (PARTITION BY col ORDER BY other DESC)
Try it yourself
Run the example below on a real PostgreSQL database, then change it and run it again. Nothing to install, no sign-up.
Examples
1. Rank within groups
SELECT category, name, price, ROW_NUMBER() OVER (PARTITION BY category ORDER BY price DESC) AS rn FROM products;
1 = most expensive in each category.
2. Top 1 per group
SELECT category, name, price FROM (SELECT category, name, price, ROW_NUMBER() OVER (PARTITION BY category ORDER BY price DESC) AS rn FROM products) t WHERE rn = 1;
Most expensive product per category.
Common mistakes
- Using ROW_NUMBER when ties should share a rank. Use RANK or DENSE_RANK.
Practice: test yourself
This challenge is from our interactive course. Write the query and press Check answer.
Return the single most expensive product in each category: category, name, price.
FAQ
Which should I use in interviews?
Say why you picked it: ROW_NUMBER for exactly one row per group, DENSE_RANK when ties should all be returned.
Learn SQL step by step
65 hands-on exercises, streaks, a leaderboard and a certificate.