SQL Ranking
Functions
Master ROW_NUMBER, RANK, and DENSE_RANK to assign meaningful positions to rows within your query results.
What Are Ranking Functions?
Ranking functions are a category of SQL window functions that assign a sequential number to each row within a partition of a result set. Unlike aggregate functions, they do not collapse rows: every row keeps its identity and gets a rank.
They answer questions like: "Who scored highest?", "What is the top-selling product?", and "Which students tied for 2nd place?"
Meet the Big Three
Why Rankings Matter
The OVER() Clause
How They Differ on Ties
ROW_NUMBER in Detail
RANK in Detail
| student_name | score | rank |
|---|---|---|
| Alice | 95 | 1 |
| Bob | 90 | 2 |
| Carol | 90 | 2 |
| David | 85 | 4 |
DENSE_RANK in Detail
| student_name | score | dense_rank |
|---|---|---|
| Alice | 95 | 1 |
| Bob | 90 | 2 |
| Carol | 90 | 2 |
| David | 85 | 3 |
Ranking Within Partitions
| department | employee | salary | dept_rank |
|---|---|---|---|
| Engineering | Ava | 120k | 1 |
| Engineering | Ben | 110k | 2 |
| Marketing | Cara | 100k | 1 |
| Marketing | Dan | 95k | 2 |
How to Apply Ranking Functions
Example: Top 3 Students
Example: Remove Duplicates
A common pattern uses ROW_NUMBER to keep only the most recent record per customer when duplicates exist:
Example: Top Seller per Region
Common Mistakes
Summary Comparison
| ROW_NUMBER | RANK | DENSE_RANK | |
|---|---|---|---|
| Unique values? | Always | Only without ties | Only without ties |
| Handles ties? | Breaks arbitrarily | Same rank | Same rank |
| Gaps after ties? | No (never ties) | Yes | No |
| Max possible value | \( N \) (row count) | \( N \) (row count) | Count of distinct values |
| Best use case | De-duplication, pagination | Competition ranking | Top-N distinct values |
Question 1 of 5
Given scores of 100, 95, 95, 90 ordered DESC, what value does RANK() assign to the row with score 90?
Question 2 of 5
Which ranking function is best for removing duplicate rows, keeping only the latest record per group?
Question 3 of 5
With values 50, 50, 40, 30 ordered DESC, what does DENSE_RANK() assign to the row with value 30?
Question 4 of 5
Why can you not write WHERE RANK() OVER(...) = 1 directly in the same SELECT query?
Question 5 of 5
What does the PARTITION BY clause do inside an OVER() window?