Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 83/ 160
05. Window Functions & Analytical SQL

Ranking Functions: ROW_NUMBER(), RANK(), DENSE_RANK()

Rank rows with and without gaps using ROW_NUMBER, RANK, and DENSE_RANK.

BeginnerROW_NUMBER · RANK · DENSE_RANK3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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.

Ranking within each departmentQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  name,3  department,4  salary,5  DENSE_RANK() OVER (6    PARTITION BY7      department8    ORDER BY9      salary DESC10  ) AS rnk11FROM12  employees;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/12
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative dense ranks4 sample rows
Representative dense ranks
namedepartmentsalaryrnk
AshaEngineering1250001
RaviEngineering1250001
MiraEngineering1000002
KunalSales900001

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.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

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.

Second-highest distinct salaryQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1WITH2  r AS (3    SELECT4      salary,5      DENSE_RANK() OVER (6        ORDER BY7          salary DESC8      ) AS d9    FROM10      employees11  )12SELECT DISTINCT13  salary14FROM15  r16WHERE17  d = 2;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · SQL expression

Read this line together with the surrounding statement as part of the same SQL expression.

1/17
3OutputInspect the representative rows, affected-row count, plan, or command status.
Second-highest distinct salary1 sample row
Second-highest distinct salary
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.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Rank in a CTE, filter outside.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1PARTITION BY

Define the groups

Decide whether the ranking restarts per group (department, category, user) or runs over the whole table.

SQL at this step
1PARTITION BY2  department
What to watch at this step
Optional
yes
Tip: use ← → to move between steps

When 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

ROW_NUMBER()
Best for: Exactly one row per group: latest record, deduplication

Strengths: Numbers are always unique.

Watch out: Ties are broken arbitrarily unless you add a tiebreaker.

RANK()
Best for: Competition-style ranking where ties push later positions down

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.

DENSE_RANK()
Best for: Nth highest distinct value; top N with ties

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 (…) = 1 instead 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?
Interview tip: Write the three outputs for 100, 90, 90, 80 side by side. It proves you know how each function treats ties, and then you can pick the one that matches the question's wording.

Knowledge check

Loading quiz

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.

Open SQL Practice →SQL interview Q&A
Previous topic
Anatomy of OVER() Clause (PARTITION BY, ORDER BY, Window Frame)
Next topic
Distribution & Bucketing Functions: NTILE(), PERCENT_RANK(), CUME_DIST()