Learn SQL
-- windows.row_number

ROW_NUMBER & Ranking in SQL

Number rows per group without collapsing them

--concept

Window functions compute a value for every row from a “window” of related rows — without grouping them away. ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) numbers employees within each department, best first, while every column stays visible. GROUP BY answers “per department” questions; windows answer “for each row, compared to its group” questions.

--how it works
1

Partition the rows

OVER (PARTITION BY department …) slices the result into per-department groups — like GROUP BY, except the rows themselves survive.

2

Order inside each partition

… ORDER BY salary DESC ranks employees best-first within their own department; the sort is (department, salary DESC) in one pass.

3

Stamp the numbers

ROW_NUMBER() walks each sorted partition assigning 1, 2, 3… — deterministic, never tied, unlike RANK().

4

Every column stays visible

The function adds a column; it removes none. Filter, join and display the result like any ordinary query.

5

Top-N per group = CTE + filter

Wrap the windowed query in a CTE, then WHERE rn <= 3 outside it — the classic “top 3 per department” interview answer.

--visualization
employees — rawAlice85kBob52kCynthia91kDavid47kElena58kFarid73kOVER (PARTITION BY department ORDER BY salary DESC)ENGICynthia91k1Alice85k2Farid73k3MARKDavid47k1SALEElena58k1Bob52k2SELECT …, ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS rn …
Engineering Marketing Sales
Stage 1 / 6
GROUP BY would collapse each department to one row. The window function keeps all six — watch the ranks arrive.
--example
query.sql
1SELECT name, department, salary,
2 ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS rn
3FROM employees ORDER BY department, rn;
Result
namedepartmentsalaryrn
CynthiaEngineering910001
AliceEngineering850002
FaridEngineering730003
DavidMarketing470001
ElenaSales580001
BobSales520002

Six rows in, six rows out — nothing is collapsed. Within Engineering the salaries 91k, 85k, 73k become positions 1, 2, 3; Sales numbers Elena before Bob; Marketing’s single row is 1. A WHERE rn = 1 (in a CTE) would return the three department toppers.

--variants

Number employees per department

Rank without collapsing — the window signature move.

query.sql
1SELECT name, department, salary,
2 ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS rn
3FROM employees
4ORDER BY department, rn;
Result
namedepartmentsalaryrn
CynthiaEngineering910001
AliceEngineering850002
FaridEngineering730003
DavidMarketing470001
ElenaSales580001
BobSales520002
1Six rows in, six rows out — GROUP BY would have returned three.
2Engineering sorts 91k → 85k → 73k and gets 1, 2, 3; Marketing’s lone row is 1.
3The engine does one sort of (department, salary DESC) and walks it stamping numbers.

Top earner per department

The window-in-CTE-then-filter pattern.

query.sql
1WITH ranked AS (
2 SELECT name, department, salary,
3 ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS rn
4 FROM employees
5)
6SELECT name, department, salary FROM ranked WHERE rn = 1;
Result
namedepartmentsalary
CynthiaEngineering91000
DavidMarketing47000
ElenaSales58000
1Inside the CTE every row gets its within-department position.
2The outer WHERE rn = 1 keeps only the first row of each partition.
3A correlated MAX subquery does the same job; on big tables the window plan is usually cheaper.

ROW_NUMBER vs RANK vs DENSE_RANK

Same input, three tie behaviours.

query.sql
1SELECT name, salary,
2 ROW_NUMBER() OVER (ORDER BY salary DESC) AS rn,
3 RANK() OVER (ORDER BY salary DESC) AS rk,
4 DENSE_RANK() OVER (ORDER BY salary DESC) AS dr
5FROM employees WHERE department = 'Engineering';
Result
namesalaryrnrkdr
Cynthia91000111
Alice85000222
Farid73000333
1No salary ties here, so all three agree — add two equal salaries and they diverge.
2With a tie at 1: RANK gives 1,1,3 (skips); DENSE_RANK gives 1,1,2; ROW_NUMBER breaks the tie arbitrarily 1,2,3.
3Pick by intent: row identity (ROW_NUMBER), competition ranking (RANK), league tiers (DENSE_RANK).

Delete duplicates with ROW_NUMBER

Keep one row per business key — a production classic.

query.sql
1WITH dups AS (
2 SELECT id,
3 ROW_NUMBER() OVER (PARTITION BY email ORDER BY id) AS rn
4 FROM staff
5)
6DELETE FROM staff USING dups
7WHERE staff.id = dups.id AND dups.rn > 1;
8-- keeps the lowest id per email, removes the rest
Result
result
2 rows deleted — one row per email remains
1Number rows within each email: the first occurrence is 1, later copies 2, 3…
2Delete where rn > 1 — duplicates die, originals live.
3Then add the UNIQUE constraint that would have prevented the mess.
--key facts
Windows ≠ GROUP BYGROUP BY outputs one row per group; windows annotate every input row
RANK vs DENSE_RANKRANK skips after ties (1,1,3); DENSE_RANK does not (1,1,2); ROW_NUMBER never ties
Top-N per groupthe classic interview pattern: ROW_NUMBER in a CTE, then filter rn <= N
--use cases
Leaderboards and “top N per group” reports
Pagination with stable ordering (rn BETWEEN 11 AND 20)
Deduplication jobs before adding UNIQUE constraints
Sessionisation: number events per user in time order
--under the hood
Window ordering is materialised with a sort of (partition, order) keys — an index matching those columns can eliminate the sort entirely.
ROW_NUMBER is non-deterministic under ties; add a unique tiebreaker column if the order matters downstream.

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Take the queries you just visualized and see the data structures that power real databases.