01 / 21
3 2 1

SQL Ranking
Functions

Master ROW_NUMBER, RANK, and DENSE_RANK to assign meaningful positions to rows within your query results.

SQL Window Functions

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

ROW_NUMBER()
Assigns a unique sequential integer to every row. No ties: even identical values get different numbers.
RANK()
Assigns the same number to tied rows, then skips the next number(s). Creates gaps in the sequence.
DENSE_RANK()
Assigns the same number to tied rows but never skips a number. The sequence is always consecutive.

Why Rankings Matter

1
Leaderboards and scoring: Display standings in games, exams, or sales dashboards where position matters.
2
Top-N queries: Efficiently retrieve the "top 5 products" or "bottom 10 performers" per category.
3
De-duplication: Use ROW_NUMBER to keep only one row per group when duplicates exist.
4
Pagination: Assign row numbers to implement efficient page-by-page result sets.

The OVER() Clause

RANK() OVER ( PARTITION BY column_a ORDER BY column_b DESC )
PARTITION BY
Divides the result set into independent groups. Ranking restarts at 1 for each partition. Optional: omit to rank all rows together.
ORDER BY
Defines the sort order that determines which row gets rank 1, rank 2, etc. Required for all three functions.

How They Differ on Ties

Score ROW_NUMBER RANK DENSE_RANK 95 1 1 1 90 2 2 2 90 3 2 2 85 4 4 skips 3! 3 no gap 80 5 5 4 TIE

ROW_NUMBER in Detail

SELECT student_name, score, ROW_NUMBER() OVER ( ORDER BY score DESC ) AS row_num FROM exam_results;

RANK in Detail

SELECT student_name, score, RANK() OVER ( ORDER BY score DESC ) AS rank FROM exam_results;
student_namescorerank
Alice951
Bob902
Carol902
David854

DENSE_RANK in Detail

SELECT student_name, score, DENSE_RANK() OVER ( ORDER BY score DESC ) AS dense_rank FROM exam_results;
student_namescoredense_rank
Alice951
Bob902
Carol902
David853

Ranking Within Partitions

SELECT department, employee, salary, RANK() OVER ( PARTITION BY department ORDER BY salary DESC ) AS dept_rank FROM employees;
departmentemployeesalarydept_rank
EngineeringAva120k1
EngineeringBen110k2
MarketingCara100k1
MarketingDan95k2

How to Apply Ranking Functions

1
Choose your function: Need unique numbers? Use ROW_NUMBER. Need ties with gaps? RANK. Need ties without gaps? DENSE_RANK.
2
Define the ORDER BY: Decide which column determines rank and whether it should be ASC or DESC.
3
Add PARTITION BY (optional): If you want rankings per group (per department, per category, per year), add a PARTITION BY clause.
4
Alias the result: Give your ranking column a meaningful name using AS (e.g., AS sales_rank).
5
Filter if needed: Wrap in a subquery or CTE and use WHERE to filter on the rank (e.g., WHERE rank = 1).

Example: Top 3 Students

SELECT * FROM ( SELECT name, gpa, DENSE_RANK() OVER ( ORDER BY gpa DESC ) AS rnk FROM students ) ranked WHERE rnk <= 3;

Example: Remove Duplicates

A common pattern uses ROW_NUMBER to keep only the most recent record per customer when duplicates exist:

SELECT * FROM ( SELECT customer_id, email, updated_at, ROW_NUMBER() OVER ( PARTITION BY customer_id ORDER BY updated_at DESC ) AS rn FROM customers ) deduped WHERE rn = 1;

Example: Top Seller per Region

WITH ranked_sales AS ( SELECT region, product, total_sales, RANK() OVER ( PARTITION BY region ORDER BY total_sales DESC ) AS sales_rank FROM product_sales ) SELECT * FROM ranked_sales WHERE sales_rank = 1;

Common Mistakes

✕ Filtering in WHERE directly
You cannot write WHERE RANK() OVER(...) = 1 in the same query. Window functions run after WHERE. Wrap in a subquery or CTE first.
✕ Missing ORDER BY
Omitting ORDER BY inside OVER() gives unpredictable results. Most databases require it for ranking functions and will error out.
✕ Confusing RANK and DENSE_RANK
Using RANK for "top 3 categories" may return fewer than 3 distinct categories if ties cause gaps. Use DENSE_RANK when you need consecutive positions.

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?