SQL RANK() is used to assign a rank or position to each row within a result set based on a specified order. Rows with the same values receive the same rank, and the next rank is skipped for ties.
- PARTITION BY: Ranks are assigned independently within each group defined by PARTITION BY.
- ORDER BY: Determines the order of ranking within the result set or within each partition.
Example: First, we will create a demo SQL table to demonstrate the RANK() function

Query:
SELECT
Name,
Department,
Salary,
RANK() OVER (ORDER BY Salary DESC) AS Rank
FROM Employees;Output:

Syntax:
RANK() OVER (
  [PARTITION BY expression, . . . ]
  ORDER BY expression (ASC | DESC) );- RANK(): Assigns a rank or position to each row based on the specified order.
- PARTITION BY (optional): Divides the result set into groups and ranks rows independently within each group.
- ORDER BY: Specifies the order for ranking in ascending (ASC) or descending (DESC) order.
Example: We will create a Student table, which stores student data including roll_no, name, age, class, and marks.

Query:
SELECT
StudentID,
Name,
Marks,
RANK() OVER (ORDER BY Marks DESC) AS Rank
FROM students;Output:

- The
RANK()function gives each student a rank based on Marks in descending order. - Students with the same marks get the same rank.
- The next rank is skipped after a tie.
RANK() vs DENSE_RANK() vs ROW_NUMBER()
Below are the comparison of the three common ranking functions in SQL Server: RANK(), DENSE_RANK(), and ROW_NUMBER().
| RANK() | DENSE_RANK() | ROW_NUMBER() |
|---|---|---|
| Assigns rank based on order | Assigns rank like RANK() but without gaps | Assigns a unique sequential number to each row |
| Same rank for tied values | Same rank for tied values | No tie handling; always unique |
| Skips rank after tie | No skipping | Consecutive numbers |