WindowSQL standard

RANK

Assigns places with ties: equal values share a place, and the next one is skipped.

Syntax

RANK() OVER (ORDER BY <sort key>)
RANK() OVER (PARTITION BY <group> ORDER BY <sort key>)

Just like in a competition: two people with the same result share second place, and the next one comes fourth, because third is already “taken”. A window function: the number of rows stays the same, and each gets its own place. PARTITION BY ranks separately within each group.

Data for the examples

employees

namedepartmentsalarybonusphone
Emmabackend1200300+44 7700 900123
Liambackend1000NULLNULL
Oliviafrontend1350150+44 7700 900456
Noahfrontend950NULL+44 7700 900789
Sophiadesign1200200NULL

These tables already exist in the sandbox — the examples below use them. Want to try this in your own database? Copy the SQL.

Places by salary
SELECT name, salary,
RANK() OVER (ORDER BY salary DESC) AS place
FROM employees;
namesalaryplace
Olivia13501
Emma12002
Sophia12002
Liam10004
Noah9505

Emma and Sophia earn the same and share second place, so Liam is fourth.

ROW_NUMBER, RANK and DENSE_RANK side by side
SELECT name, salary,
ROW_NUMBER() OVER (ORDER BY salary DESC) AS row_number,
RANK() OVER (ORDER BY salary DESC) AS rank,
DENSE_RANK() OVER (ORDER BY salary DESC) AS dense_rank
FROM employees;
namesalaryrow_numberrankdense_rank
Olivia1350111
Emma1200222
Sophia1200322
Liam1000443
Noah950554
The top two salaries, ties includedAdvanced
SELECT name, salary
FROM (
SELECT name, salary,
RANK() OVER (ORDER BY salary DESC) AS place
FROM employees
) ranked
WHERE place <= 2;
namesalary
Olivia1350
Emma1200
Sophia1200

Three people come out, because two share second place. With ROW_NUMBER, one of them would drop out.

Watch out

After a tie, places are skipped: 1, 2, 2, 4. If you need no gaps — 1, 2, 2, 3 — use DENSE_RANK.

Without ORDER BY in OVER, all rows count as equal and get place 1.

You can't use the place in the WHERE of the same query — calculate it in a subquery first and filter outside it.

Related functions

Learn more in the course