Welcome to our comprehensive SQL RANK() tutorial! Today, we'll dive into understanding the powerful SQL RANK() function and how it can help you sort and analyze your data more effectively.
The SQL RANK() function is a powerful tool that assigns a unique rank to each row in a result set based on the order of the rows. This function is useful when you want to assign ranks to a group of records, such as determining the rank of a student in a class or the rank of a product in sales.
The basic syntax of the SQL RANK() function is:
RANK() OVER (ORDER BY column_name)Let's consider an example where we have a table named students:
CREATE TABLE students (
id INT PRIMARY KEY,
name VARCHAR(255),
score INT
);
INSERT INTO students (id, name, score)
VALUES (1, 'John', 95), (2, 'Mike', 88), (3, 'Alice', 90), (4, 'Bob', 92), (5, 'Emily', 90);To find the rank of each student based on their score, we can use the RANK() function as follows:
SELECT id, name, score, RANK() OVER (ORDER BY score DESC) AS rank
FROM students;This will return:
id | name | score | rank
--:|------|------:|-----:
1 | John | 95 | 1
5 | Emily | 90 | 2
4 | Bob | 92 | 3
3 | Alice | 90 | 3
2 | Mike | 88 | 5
As you can see, the RANK() function correctly assigns ranks based on the scores.
In some cases, you might need to handle ties in the data. To do this, you can use the DENSE_RANK() function. This function assigns consecutive ranks to all the rows without gaps. Let's modify our previous example to include this:
SELECT id, name, score, DENSE_RANK() OVER (ORDER BY score DESC) AS rank
FROM students;This will return:
id | name | score | rank
--:|------|------:|-----:
1 | John | 95 | 1
5 | Emily | 90 | 2
4 | Bob | 92 | 3
3 | Alice | 90 | 3
2 | Mike | 88 | 5
As you can see, the students with a score of 90 (Alice and Emily) both have a rank of 3, demonstrating the handling of ties with the DENSE_RANK() function.
What is the purpose of the SQL RANK() function?
Happy learning! 📝💡🎯