SQL RANK Function Example
Let’s look at some examples of the RANK function in SQL server to understand how it’s working.
Let’s create a demo table on which we will perform the RANK statement. Write the following queries to create a table “geek_demo”.
CREATE TABLE geek_demo (Name VARCHAR(10) );
INSERT INTO geek_demo (Name)
VALUES ('A'), ('B'), ('B'), ('C'), ('C'), ('D'), ('E');
SELECT * FROM sales.geek_demo;
Output
Name |
---|
A |
B |
B |
C |
C |
D |
E |
In this example, we will use RANK() to assign ranks to the rows in the result set of the geek_demo table.
Query:
SELECT Name,
RANK () OVER (
ORDER BY Name
) AS Rank_no
FROM geek_demo;
Output –
Name | Rank_no |
---|---|
A | 1 |
B | 2 |
B | 2 |
C | 4 |
C | 4 |
D | 6 |
E | 7 |
RANK() Function in SQL Server
SQL RANK() function is a window function used in SQL Server that calculates the rank of each row of the result set.
Contact Us