SQL RANK Function

Quick summary: The SQL RANK() function ranks rows within a partition, allowing ties.

SQL RANK Syntax

RANK() OVER ( [PARTITION BY column] ORDER BY column )
SQL

SQL RANK Basic examples

SELECT score, RANK() OVER (ORDER BY score DESC) FROM results;
SQL
Output:
Ranks with gaps

Equal values receive the same rank.

SQL RANK Real-world usage

SELECT user_id, RANK() OVER (ORDER BY SUM(total) DESC) FROM orders GROUP BY user_id;
SQL
Output:
Revenue ranking

Ranks users by aggregated totals.

SQL RANK Edge cases

SELECT RANK() OVER (ORDER BY NULL) FROM users;
SQL
Output:
All rows rank 1

No ordering means identical rank.

SQL RANK Common mistakes

Expecting consecutive ranks

RANK creates gaps after ties.

Incorrect
RANK()
Correct
DENSE_RANK()

Use DENSE_RANK for consecutive values.

SQL RANK Frequently Asked Questions

What does RANK() do in SQL?

Assigns rank with gaps for ties.

Use case of RANK()?

Ranking with duplicates.

Syntax?

RANK() OVER (ORDER BY column).

Difference from ROW_NUMBER()?

RANK allows ties.

Handles duplicates?

Same rank for equal values.

Gaps in ranking?

Yes.

Common mistake?

Expecting continuous numbers.

Used with PARTITION BY?

Yes.

Return type?

Integer.

Performance?

Moderate.

Used in leaderboards?

Yes.

Best practice?

Use when ties matter.

SQL RANK Related SQL Keywords