Ranking Functions: ROW_NUMBER(), RANK(), DENSE_RANK()
Rank rows with and without gaps using ROW_NUMBER, RANK, and DENSE_RANK.
In plain words
They give each row a position number inside its group. They only disagree about what to do with ties.
Think of it like…
A race: ROW_NUMBER hands out finishing positions even when two runners cross together; RANK gives both of them 1st and the next runner 3rd, like the Olympics; DENSE_RANK gives both 1st and the next runner 2nd.
Where you’ve seen it
Salaries 100, 90, 90, 80 in descending order: ROW_NUMBER gives 1, 2, 3, 4; RANK gives 1, 2, 2, 4; DENSE_RANK gives 1, 2, 2, 3. For "third-highest distinct salary", DENSE_RANK = 3 returns 80, while RANK = 3 returns nothing.
Words you’ll hear
- PARTITION BY
- Restarts the numbering for each group, such as each department.
- ORDER BY (inside OVER)
- Defines the ranking order. Required for ranking functions.
- Tie
- Rows with equal values in the ORDER BY columns.
- Tiebreaker
- An extra unique ORDER BY column that makes ROW_NUMBER give the same result on every run.
Visual diagram
Theory & example queries
Same window, different tie rules
All three take the same OVER clause: an optional PARTITION BY to restart per group, and an ORDER BY that defines who comes first. Without PARTITION BY, the whole result set is one window.
ROW_NUMBER always produces 1..n with no repeats. When rows tie on the ORDER BY columns, which tied row gets which number is arbitrary and can change between runs, so add a unique column like id to the ORDER BY to make it deterministic.
SELECT name, department, salary, DENSE_RANK() OVER ( PARTITION BY department ORDER BY salary DESC ) AS rnkFROM employees;PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Representative dense ranks4 sample rows
| name | department | salary | rnk |
|---|---|---|---|
| Asha | Engineering | 125000 | 1 |
| Ravi | Engineering | 125000 | 1 |
| Mira | Engineering | 100000 | 2 |
| Kunal | Sales | 90000 | 1 |
Note: Sample rows show tied Engineering salaries receiving the same dense rank without a skipped value. Output row order is not guaranteed without a final ORDER BY.
Key takeaway: Choose by tie behaviour: unique (ROW_NUMBER), gaps (RANK), no gaps (DENSE_RANK).
Filtering on a rank
Window functions are computed after WHERE, so WHERE rnk = 1 in the same query fails. Compute the rank in a subquery or CTE and filter outside it, or use QUALIFY in Snowflake, BigQuery or DuckDB.
"Latest row per user" is ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC) = 1. "All top earners, including ties" is RANK() = 1 or DENSE_RANK() = 1. PostgreSQL also has DISTINCT ON (user_id) as a shortcut for the first case.
WITH r AS ( SELECT salary, DENSE_RANK() OVER ( ORDER BY salary DESC ) AS d FROM employees )SELECT DISTINCT salaryFROM rWHERE d = 2;PostgreSQL is the lesson baseline unless noted otherwise.
Read this line together with the surrounding statement as part of the same SQL expression.
Second-highest distinct salary1 sample row
| salary |
|---|
| 95000 |
Note: The sample assumes the highest distinct salary is 125000 and the next is 95000. All employees tied at 95000 collapse to one row because DISTINCT is applied outside the ranking CTE.
Key takeaway: Rank in a CTE, filter outside.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Define the groups
Decide whether the ranking restarts per group (department, category, user) or runs over the whole table.
PARTITION BY departmentWhen to use it & trade-offs
What it is
ROW_NUMBER(), RANK() and DENSE_RANK() number rows within a window in a given order. They differ only on ties: ROW_NUMBER gives tied rows different numbers (1, 2, 3), RANK gives ties the same number and then skips (1, 1, 3), and DENSE_RANK gives ties the same number without a gap (1, 1, 2).
Why it matters: "Nth highest salary", "top 3 products per category" and "latest record per user" are all ranking problems, and the right function depends on how ties should behave. It's one of the most-asked SQL topics in data and backend interviews.
When to reach for it
- Nth highest salary or price
- Top N per category
- Keeping the latest row per key during deduplication
When to avoid or be careful
- ROW_NUMBER for "Nth highest" when values can tie
- ROW_NUMBER without a tiebreaker in production pipelines
- Filtering on the rank in the WHERE of the same SELECT
ROW_NUMBER vs RANK vs DENSE_RANK
Strengths: Numbers are always unique.
Watch out: Ties are broken arbitrarily unless you add a tiebreaker.
Strengths: Tied rows share a rank, and a rank tells you how many rows are ahead.
Watch out: Gaps (1, 1, 3), so "rank = 2" can return nothing.
Strengths: Tied rows share a rank and there are no gaps.
Watch out: "Top N" can return more than N rows.
Interview signals & numbers to know
When this topic comes up
- “Second highest salary”
- “Top 3 per category”
- “Latest record per user”
- Ties
- “Remove duplicates but keep one”
Benchmarks & rules of thumb
- ROW_NUMBER
- 1, 2, 3, 4
- RANK
- 1, 2, 2, 4
- DENSE_RANK
- 1, 2, 2, 3
Common mistakes & follow-ups
Common interview mistakes
- Answering "second highest salary" with ROW_NUMBER and returning a tied top value.
- Writing
WHERE ROW_NUMBER() OVER (…) = 1instead of filtering in an outer query. - Forgetting PARTITION BY and ranking across all groups at once.
Likely interviewer follow-ups
- How would you find the Nth highest salary in each department?
- What changes in your answer if two employees tie for first place?
- How would you get the latest row per user without window functions?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Ranking Functions: ROW_NUMBER(), RANK(), DENSE_RANK() with hands-on SQL practice and interview Q&A.