RANK() assigns a competition-style rank to each row. Rows with equal
ORDER BY values receive the same rank, and the next rank skips
the number of tied rows (like Olympic medal standings).
Ordered values: [10, 20, 20, 40]
RANK(): [1, 2, 2, 4]
RANK()
from DENSE_RANK().01_ROW_NUMBER06_CTEs)SELECT
column_a,
RANK() OVER (ORDER BY sort_column) AS rank_value
FROM table_name;
employes, departments, locations
See 02_rank.sql.
| Domain | Scenario |
|---|---|
| Sales | Rank reps by revenue, allowing ties for shared bonuses |
| Education | Rank students by exam score with shared placements |
| Manufacturing | Rank suppliers by defect rate |
RANK()’s gap behavior with DENSE_RANK()’s no-gap behavior.ORDER BY column(s)
inside OVER() – not by any other column in the SELECT list.WHERE (same restriction as
ROW_NUMBER() – use a CTE).RANK() deliberately when business rules require gaps after
ties (e.g., “rank 1 and 2 both get gold, next place is rank 3 not 3rd
overall position”).RANK() was chosen over DENSE_RANK() –
future maintainers should not have to guess.RANK() and DENSE_RANK() share the same sorting cost as ROW_NUMBER()
but additionally require a tie-comparison against the previous row’s
ORDER BY value, evaluated during the same single pass.
emp_id.rank = 1.ROW_NUMBER() and RANK() side by side on manager_id.Beginner
20–25 minutes
RANK() output on a dataset containing ties.RANK() and
ROW_NUMBER().← Previous: 01_ROW_NUMBER
↑ Module README
→ Next: 03_DENSE_RANK