Introduction
Rank functions in SQL are used to assign a rank to each row within a partition of a result set. These functions are useful for a variety of applications, such as finding the top N records in a group, generating unique rankings for rows, and more. The four primary rank functions in SQL are,
RANK()
Assigns a unique rank to each distinct row within the partition. If two rows have the same rank, the next rank value is skipped.
Script
Explanation
In this example, we are trying to get a salesperson who has max sales, and based on that, we are providing a Rank.
Shiv and Madhu have the same Sales amount, so both have Rank 4.
Key Point
We can see Pankaj should be 5 but Rank does not maintain sequence, we can fix this in dense rank.
![Dense rank]()
DENSE_RANK(): Similar to RANK(), but does not skip rank values in the case of ties.
Having the same example and script above now I am going to add the Dense rank Column.
Result
![Result]()
Explanation
We can see that the Column Dense Rank maintains the sequence.
ROW_NUMBER()
Assigns a unique sequential integer to rows within the partition of a result set, starting at 1.
This simply adds a sequence number to each row.
New script
Result
![SQL Query]()
More Examples
Find Nth Highest salary with Rank()
We are trying to find the 4th Highest salary.
Script
![Run]()
Ranking Employees by Salary Within Departments.
In a company, you might want to rank employees by their salary within each department to identify the top earners in each department.
Script
We have made a partition based on the department and got the desired result.
![Desired result]()