Careeroza
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
| ProductName | Price | RowNum | Rnk | DenseRnk |
|---|---|---|---|---|
| Espresso Beans 1kg | 18 | 1 | 1 | 1 |
| Basmati Rice 5kg | 12.5 | 2 | 2 | 2 |
| Olive Oil 1L | 9.99 | 3 | 3 | 3 |
| Cashews 500g | 9.99 | 4 | 3 | 3 |
| Almonds 500g | 8.25 | 5 | 5 | 4 |
| Green Tea 100 bags | 6.75 | 6 | 6 | 5 |
| Dark Chocolate | 3.49 | 7 | 7 | 6 |
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
| Department | FirstName | Salary |
|---|---|---|
| Finance | Fatima | 80000 |
| Sales | Rahul | 72000 |
| Support | James | 67000 |
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
| OrderID | Amount | Quartile |
|---|---|---|
| 107 | 27 | 1 |
| 104 | 56.25 | 1 |
| 102 | 89.9 | 2 |
| 105 | 150 | 2 |
| 108 | 198.4 | 3 |
| 101 | 245.5 | 3 |
| 106 | 320.75 | 4 |
| 103 | 412 | 4 |