RANK
RANK is a window function in SQL that assigns a unique rank to each distinct row within a partition of a result set. The rows with equal values receive the same rank, causing gaps in the sequential ranking.
RANK() OVER ( [PARTITION BY partition_expression] ORDER BY sort_expression [ASC | DESC])
Example
Output
Explanation
The example code ranks each row of the ‘Products’ table by the ‘price’ column in descending order; this is done with the RANK()
function. The function arranges the prices from the highest to the lowest. The rank of each row is displayed in the ‘PriceRank’ column.
RANK() OVER ([PARTITION BY partition_expression, … ] ORDER BY sort_expression [ASC | DESC], …)
Example
Output
Explanation
The RANK function is used to rank the rows based on the values of sales in descending order. The row with the highest sales gets a rank of 1, the next highest sales gets a rank of 2, and so on.
RANK() OVER ( [PARTITION BY value_expression , … [ n ] ] ORDER BY clause)
Example
Output
Explanation
The RANK function is being used to rank the sales by each person. It has been partitioned by the ‘SalesPerson’ column, meaning each seller gets a separate ranking starting from 1. The ORDER BY clause in the OVER function sorts the ‘Sales’ in descending order, meaning the product with the highest sales gets the top rank (1).
RANK() OVER ([<partition_by_clause>] ORDER BY <order_by_clause>)
Example
Output
Explanation
In this example, the RANK()
function is used to create a ranking of employees’ salaries within each department. The ranking is ordered by salary in descending order, meaning an employee with the highest salary in their department will be ranked first. The PARTITION BY
clause is used to split the data into partitions based on the department, meaning the rank resets for each department.