Understanding the RANK() Function in SQL with Practical Examples

Understanding the RANK() Function in SQL with Practical Examples

This article provides a better description of the SQL RANK() and with a way of executing such as well as its utility. We shall discuss how, when an ordering is specified, RANK () assigns ranks by row to a partition of a result set. It includes some example with sample tables data. The RANK() function assigns a rank to each row within a partition and it is based on the order of the specified column (or columns). It is also here that equal rankings are given to two or more rows sharing the same value of the column or columns used in the ranking. Due to missing the next level in the ranking, it also has elements where there are gaps in the ranking sequence.

Overview of RANK()

Each row inside a partition of a result set is given a rank by the SQL window function RANK(). The OVER() clause's supplied ORDER BY clause serves as the basis for the rank. The same rank is given to rows that have similar values for the ordering criteria. The number of rows with the same rank is added to the next rank. This implies that the ranking sequence may have pauses caused by RANK().

The following is the RANK() function's fundamental syntax: 

  1. RANK() OVER (  
  2.     [PARTITION BY column1, column2, ...]  
  3.     ORDER BY column3 [ASC | DESC], column4 [ASC | DESC], ...  
  4. )  
  • PARTITION BY (Optional): A clustering of the result set. The ranks of each of the partitions are considered independently. When the PARTITION BY is not provided, the whole result set is considered as one partition.
  • ORDER BY: Contains the name of the column(s) which specify the ranking order in each partition. The default order is ASC (ascending) and reverse order can be in descending order.
  • OVER(): Defines the window (set of rows) to which the function applies. 
 Example:

Let's consider a table named Employees with the following structure and data:

  1. --create objects Employees   
  2. CREATE TABLE Employees (         
  3. EmployeeID INT PRIMARY KEY    
  4. ,Department VARCHAR(50)    
  5. ,Salary DECIMAL(10, 2)     
  6. );    
  7.   
  8.     
  9. -- insert  in Employees   
  10. INSERT INTO Employees (EmployeeID, Department, Salary)     
  11. VALUES    
  12.  (1, 'Sales', 60000.00),    
  13.  (2, 'Marketing', 55000.00),     
  14. (3, 'Sales', 70000.00),     
  15. (4, 'IT', 80000.00),     
  16. (5, 'Marketing', 55000.00),     
  17. (6, 'IT', 90000.00),     
  18. (7, 'Sales', 70000.00),     
  19. (8, 'HR', 65000.00),     
  20. (9, 'HR', 75000.00),     
  21. (10, 'IT', 85000.00);    

Example 1: Ranking Employees by Salary


the objective was to rank the employees according to the salary paid.
We can tabulate the employees in the terms of salary throughout the company.
  1. --get data   Employees  
  2.   
  3. SELECT EmployeeID, Department, Salary ,RANK() OVER (ORDER BY Salary DESCAS SalaryRank    
  4. FROM    Employees;


  1. --OutPut    
  2.   
  3. EmployeeID  Department                     Salary                         SalaryRank  
  4. ----------- ------------------------------ ------------------------------ --------------------  
  5. 6           IT                             90000.00                       1  
  6. 10          IT                             85000.00                       2  
  7. 4           IT                             80000.00                       3  
  8. 9           HR                             75000.00                       4  
  9. 3           Sales                          70000.00                       5  
  10. 7           Sales                          70000.00                       5  
  11. 8           HR                             65000.00                       7  
  12. 1           Sales                          60000.00                       8  
  13. 2           Marketing                      55000.00                       9  
  14. 5           Marketing                      55000.00                       9  

This table demonstrates the hierarchy of every employee based on the salary.

Workers of identical salary receive identical rank. As salaries increase or decrease so does the rank. Employees 3 and 7 are at the same salary and will hence have same rank 5. The sixth rank, rank 6 is avoided as no one makes that much.

Example 2: Listing the employees in terms of salary wise in each department.

This is just an illustration of ranking the employees based on salary at the workplace. 
  1. SELECT EmployeeID,Department,Salary
  2. ,RANK() OVER (PARTITION BY Department ORDER BY Salary DESCAS DepartmentSalaryRank  
  3. FROM  Employees;  
 
  1. --output  
  2.   
  3. EmployeeID  Department                     Salary                         DepartmentSalaryRank  
  4. ----------- ------------------------------ ------------------------------ --------------------  
  5. 9           HR                             75000.00                       1  
  6. 8           HR                             65000.00                       2  
  7. 6           IT                             90000.00                       1  
  8. 10          IT                             85000.00                       2  
  9. 4           IT                             80000.00                       3  
  10. 5           Marketing                      55000.00                       1  
  11. 2           Marketing                      55000.00                       1  
  12. 3           Sales                          70000.00                       1  
  13. 7           Sales                          70000.00                       1  
  14. 1           Sales                          60000.00                       3  
 The given example illustrates the ranking of employees by salary by department.
The column of DepartmentSalaryRank contains the rank of every employee within his/her department. The SELECT statement clause PARTITION BY Department is a command to SQL to rank employees individually in each department. In the instance of the Sales department, the top two earners are employee 3 and employee 7 hence they all have rank 1.

Example 3: Using RANK() with a Common Table Expression (CTE)

This example demonstrates how to use RANK() within a CTE to filter the results based on the rank.
 
  1. WITH RankedEmployees AS (  
  2. SELECT  
  3. EmployeeID,Department,Salary  
  4. ,RANK() OVER (PARTITION BY Department ORDER BY Salary DESCAS DepartmentSalaryRank  
  5. FROM Employees  
  6. )  
  7. SELECT  
  8. EmployeeID,Department,Salary  
  9. FROM RankedEmployees   
  10. WHERE DepartmentSalaryRank = 1;  
  1. --output  
  2. EmployeeID  Department                     Salary  
  3. ----------- ------------------------------ ------------------------------  
  4. 9           HR                             75000.00  
  5. 6           IT                             90000.00  
  6. 5           Marketing                      55000.00  
  7. 2           Marketing                      55000.00  
  8. 3           Sales                          70000.00  
  9. 7           Sales                          70000.00  
The query initializes all employees arranged by salary in each department using RANK () function in CTE RankedEmployees. The outer query will then only pick those that have DepartmentSalaryRank=1 giving the best-paid employee (or employees) per department.

Conclusion:
 
RANK() assigns a rank to each row in a result set based on the order in which you specify. You may sort by the best performers, analyze the distribution of data, or even sort by rank. In order to get optimal use of the RANK(), you must know the meaning of PARTITION BY and ORDER BY in the OVER() clause. Remember that RANK() can omit numbers when the ordering values are equal. To enhance your queries, you can apply CTEs which allow you to divide the complicated queries into simpler and more understandable ones and unveil more data about your information. 
 

 
 

1 Comments

Nikhil Reply

good

Post Comment

Your email address will not be published. Required fields are marked *