SQL Query to Add Ranking Positions of Rows in a Database With RANK()
Last Updated :
13 Apr, 2021
In this article, we will discuss the overview of SQL function RANK and then our main focus will be on Add Ranking Positions of Rows in a Database With RANK() in SQL. Let’s discuss it one by one.
Overview :
Generally, when max/min commands are executed, a single row is displayed as output. RANK() is an SQL function introduced in order to rank the rows according to some attribute in the table. Based on the record of the existing value, the RANK function will help the column to be ranked accordingly.
Syntax :
RANK() OVER(ORDER BY Any Column)
Steps to implement RANK function :
Here, we will discuss the steps to implement the RANK function in SQL.
Step-1: Reference table :
Consider a table is created based on marks of students in the class that contains data displayed below.
ID |
NAME |
MATHEMATICS
|
PHYSICS |
CHEMISTRY |
501 |
Surya |
99
|
97 |
85
|
502 |
Sravan |
91
|
98 |
94
|
503 |
Charan |
99
|
93 |
88
|
504 |
Ram |
92
|
99 |
92
|
505 |
Aryan |
94
|
99 |
88
|
506 |
Sathwik |
91
|
88 |
91
|
507 |
Madhav |
90
|
97 |
89
|
Step-2: Creating a table :
Now, the SQL statement used to create the table is given as follows.
CREATE TABLE MarkList
(
id int,
name varchar(20),
mathematics int,
physics int,
chemistry int
);
Step-3: Inserting data :
Here, we will insert the rows into the table as follows.
insert into MarkList values( 501,'Surya',99,97,85);
insert into MarkList values(502,'Charan',99,93,88);
insert into MarkList values(503,'Sravan',91,98,94);
insert into MarkList values(504,'Ram',92,99,82);
insert into MarkList values(505,'Aryan',94,99,88);
insert into MarkList values(506,'Sathwik',91,88,91);
insert into MarkList values(507,'Madhav',90,97,89);
Step-4: Verifying and ranking data :
Now, if we want ranks based on the scores of mathematics, then the query is written as follows.
SELECT id, name, mathematics,
RANK() OVER(ORDER BY Mathematics DESC)
as
'Rank' from MarkList;
Output :
The output will be as follows.
ID |
NAME |
MATHEMATICS
|
RANK |
501 |
Surya |
99
|
1
|
502 |
Charan |
99
|
1
|
505 |
Aryan |
94
|
3
|
504 |
Ram |
92
|
4
|
506 |
Sathwik |
91
|
5
|
503 |
Sravan |
91
|
5
|
507 |
Madhav |
90
|
7
|
Explanation :
- When the SQL command is executed, the function checks for the order and assigns the ranks to the respective rows.
- Then the table is displayed with the ranks as per the given code.
Other Methods :
There are many other methods that can be used in the place of RANK(). Some of them are listed here.
- ROW_NUMBER() just adds the row number in the place of the rank.
- DENSE_RANK() just gives the next number as the next rank. This does not depend on the frequency of other ranks.
Similar Reads
PL/SQL Query to List the Last 5 Rows of a Result Set
Fetching or displaying the last five rows is a common task. Whether fetching trending topics or tracking a user's recent activity, fetching the last five rows will help in these situations. These are a few use cases we have discussed, there are many more. Product recommendation is crucial if you are
5 min read
How to Select the Nth Row in a PostgreSQL Database Table?
In PostgreSQL, selecting specific rows is a fundamental operation frequently required for tasks such as data analysis, pagination, and reporting. The "nth" row refers to the row in a table that holds a particular position or rank, where "n" represents that specific position or ranking number. This a
5 min read
Ranking Rows of Pandas DataFrame
To rank the rows of Pandas DataFrame we can use the DataFrame.rank() method which returns a rank of every respective index of a series passed. The rank is returned on the basis of position after sorting. Example #1 : Here we will create a DataFrame of movies and rank them based on their ratings. # i
2 min read
Finding the Quantile and Decile Ranks of a Pandas DataFrame column
A Quantile is where a sample is divided into equal-sized, adjacent, subgroups. The median is a quantile; the median is placed in a probability distribution so that exactly half of the data is lower than the median and half of the data is above the median. The median cuts a distribution into two equa
4 min read
SQL Server Row_Number Function With PARTITION BY
The row number function is one of the window functions used for assigning the row number to the rows in each of the partitions in the order in which they were sorted in the partition using the PARTITION clause, PARTITION only the ORDER clause can be used inside the OVER clause in such case the whole
5 min read
How to Use SQL DISTINCT and TOP in Same Query?
Structured Query Language (SQL) is a computer language used to interact with relational databases. It allows us to organize, manage, and retrieve data efficiently. In this article, we will explain how to use the DISTINCT keyword and the TOP clause together in a query, explaining their purpose, usage
4 min read
List the Last 5 Rows of a Result Set in PostgreSQL
PostgreSQL provides several methods to retrieve data from tables. One common approach involves using the SELECT statement with ORDER BY to sort data, with the option to use DESC for descending order. By understanding these basics, we can explore techniques to list the last few rows of a result set i
4 min read
PL/SQL Query to List the Last 25% Rows in a Result Set
We sometimes need to fetch some specific rows from our result set. There are many reasons to do so. When we are working on real-time analytics, focusing on recent data is then our need. This helps us in quicker decision-making as it provides us the quicker insight into the latest data. PL/SQL is a p
5 min read
How to Get Multiple Counts With Single Query in SQLite?
In data analysis, obtaining multiple counts for different categories is a common requirement. SQLite, a lightweight and versatile database management system, offers a powerful feature that allows us to achieve this efficiently. In this article, we'll explore how to use SQLite to retrieve multiple co
3 min read
Rank and Dense Rank in SQL Server
In the world of SQL, the ability to rank data based on specific criteria is important for a wide range of analytical tasks. SQL Server offers powerful functions like RANK() and DENSE_RANK(), which allow users to assign ranks to rows in a dataset. These functions are particularly useful for tasks suc
7 min read