SQL Cookbook Lesson

How to add ranking positions of rows with RANK in SQL

Learn how to add ranking positions of rows with RANK in SQL with examples and explanations from SQLPad.

Problem

You want to add ranking positions to rows in your SQL table using the RANK() function.

Sample data

Let's assume we have a Students table with the following data:

ID Name Marks
1 Alice 85
2 Bob 90
3 Charlie 80
4 David 95
5 Eve 90

MySQL Solution

SELECT ID, Name, Marks,
RANK() OVER(ORDER BY Marks DESC) RankPosition
FROM Students;

MySQL Explanation

In MySQL, the RANK() function is a window function that assigns a unique rank to each row within a result set. The rows with equal values receive the same rank, and the next rank is skipped. In this case, the RANK() function is used to assign a rank to each student based on their marks, with the student with the highest marks receiving a rank of 1. The OVER(ORDER BY Marks DESC) clause specifies that the ranking should be done in descending order of marks.

PostgreSQL Solution

SELECT ID, Name, Marks,
RANK() OVER(ORDER BY Marks DESC) RankPosition
FROM Students;

PostgreSQL Explanation

The RANK() function in PostgreSQL works the same way as in MySQL. It is a window function that assigns a unique rank to each distinct row within a result set. The rows with equal values receive the same rank, and the next rank is skipped. In this case, the RANK() function is used to assign a rank to each student based on their marks, with the student with the highest marks receiving a rank of 1. The OVER(ORDER BY Marks DESC) clause specifies that the ranking should be done in descending order of marks.

Keep Practicing

Related Cookbook Lessons

View all lessons

Interview Prep

Begin Your SQL, Python, and R Journey

Master 230 interview-style coding questions and build the data skills needed for analyst, scientist, and engineering roles.