Ranking Functions

ROW_NUMBER, RANK, DENSE_RANK

The three differ only in how they treat ties:

Example

Rank products by price. Two products could tie; we add one to show the difference:

INSERT INTO Products (ProductID, ProductName, Category, Price, Stock)
VALUES (7, 'Cashews 500g', 'Snacks', 9.99, 30);

SELECT ProductName, Price,
       ROW_NUMBER() OVER (ORDER BY Price DESC) AS RowNum,
       RANK()       OVER (ORDER BY Price DESC) AS Rnk,
       DENSE_RANK() OVER (ORDER BY Price DESC) AS DenseRnk
FROM Products;

Result: 7 rows

ProductNamePriceRowNumRnkDenseRnk
Espresso Beans 1kg18111
Basmati Rice 5kg12.5222
Olive Oil 1L9.99333
Cashews 500g9.99433
Almonds 500g8.25554
Green Tea 100 bags6.75665
Dark Chocolate3.49776
  • ROW_NUMBER: always 1, 2, 3, 4... (ties get different numbers).
  • RANK: ties share a rank, then numbers are skipped (1, 2, 2, 4).
  • DENSE_RANK: ties share a rank, no gaps (1, 2, 2, 3).

Top N per Group

Example

The highest-paid employee in each department, a very common interview task:

WITH Ranked AS (
  SELECT FirstName, Department, Salary,
         ROW_NUMBER() OVER (PARTITION BY Department ORDER BY Salary DESC) AS rn
  FROM Employees
)
SELECT Department, FirstName, Salary
FROM Ranked
WHERE rn = 1;

Result: 3 rows

DepartmentFirstNameSalary
FinanceFatima80000
SalesRahul72000
SupportJames67000

NTILE

Example

Split orders into 4 buckets (quartiles) by amount:

SELECT OrderID, Amount, NTILE(4) OVER (ORDER BY Amount) AS Quartile
FROM Orders;

Result: 8 rows

OrderIDAmountQuartile
107271
10456.251
10289.92
1051502
108198.43
101245.53
106320.754
1034124