Ranking (ROW_NUMBER, RANK, DENSE_RANK)
Rank rows within partitions using ROW_NUMBER (unique), RANK (skips ties), and DENSE_RANK (no gaps).
Ranking (ROW_NUMBER, RANK, DENSE_RANK) is an essential topic in SQL and relational database engineering.
Overview
Building on foundational principles introduced in partition-by, mastering ranking (row_number, rank, dense_rank) provides the core mental model and practical query skills needed for production relational database engineering.
SELECT
name, score,
ROW_NUMBER() OVER (ORDER BY score DESC) AS row_num,
RANK() OVER (ORDER BY score DESC) AS rank_num,
DENSE_RANK() OVER (ORDER BY score DESC) AS dense_rank_num
FROM leaderboard;
Key Concepts
- Understand the fundamental syntax, conventions, and mental model.
- Avoid common beginner traps, data type mismatches, and performance pitfalls.
- Apply practical idioms directly in production applications.
[!TIP] Master this concept to build a rock-solid foundation. Next, proceed to lag-lead-offsets.