SQL ROW_NUMBER and RANK

Assign sequential rankings and partitioned row numbers to query rows.

Window ranking functions calculate positions within a result set: ROW_NUMBER() assigns unique sequential integers, while RANK() leaves gaps when values tie, and DENSE_RANK() does not leave gaps.

Key Takeaways: SQL ROW_NUMBER and RANK

Mastering SQL ROW_NUMBER and RANK helps you write clean and reliable SQL code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

SQL ROW_NUMBER and RANK Code Example

SQL
SELECT name, salary,
       ROW_NUMBER() OVER (ORDER BY salary DESC) AS row_num,
       RANK() OVER (ORDER BY salary DESC) AS rank_pos
FROM employees;
Output
Returns employees sorted by salary with sequential row numbers
Free sign-in required · Google login available
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services