How to use the RANK() Function in SQL?

The RANK() function is a window function could be used to calculate a rank for each row within a partition of a result set.

The same rank is assigned to the rows in a partition which have the same values. The rank of the first row is 1. The ranks may not be consecutive in the RANK() function as it adds the number of repeated rows to the repeated rank to calculate the rank of the next row.

Syntax :

RANK() OVER (
   [PARTITION BY expression, ]
   ORDER BY expression (ASC | DESC) );

Example –

Let us create a table geek_demo that has only column Name :

CREATE TABLE geek_demo (Name VARCHAR(10) );

Now, insert some rows into the sales.rank_demo table:

INSERT INTO geek_demo (Name) 

VALUES('A'), ('B'), ('B'), ('C'), ('C'), ('D'), ('E');



Select data from the geek_demo table: 

SELECT * 
FROM sales.geek_demo;

Output:

Name
A
B
B
C
C
D
E