ROW_NUMBER, RANK, DENSE_RANK: Concept
Module: Window Functions
Think of these three functions as different ways to assign positions in a race. ROW_NUMBER is like giving each runner a unique bib number - everyone gets a different number (1, 2, 3, 4, 5, 6) even if they cross the finish line at exactly the same time. RANK is like official race results - tied runners get the same position, but the next position skips ahead (1st, 2nd, 2nd, 4th, 4th, 6th). DENSE_RANK is like medal categories - tied runners get the same medal level, but the next level continues in sequence (Gold, Silver, Silver, Bronze, Bronze, Participation). Your choice depends on what makes sense for your business logic.
**
**ROW_NUMBER() - The Sequential Counter:**
ROW_NUMBER assigns a unique number to every row, starting from 1. It's completely deterministic within a session but handles ties arbitrarily.
```sql
-- Perfect for pagination
SELECT
product_name,
price,
ROW_NUMBER() OVER(ORDER BY price DESC, product_id) as position
FROM products
WHERE category = 'Laptops';
-- Result: 1, 2, 3, 4, 5... (always sequential)
-- Even if 10 laptops have same price, each gets unique position
```
**ROW_NUMBER Use Cases:**
- ✅ **Pagination**: "Show items 21-40" requires unique positions
- ✅ **Unique IDs**: When you need to assign sequential identifiers
- ✅ **Sampling**: "Every 10th record" or "First 100 records"
- ✅ **Deduplication**: Keep first occurrence of duplicates
**RANK() - The Fair Competition Judge:**
RANK gives tied values the same rank but skips the next ranks. This mimics real competition scoring.
```sql
-- Sales contest with fair tie handling
SELECT
salesperson_name,
monthly_sales,
RANK() OVER(ORDER BY monthly_sales DESC) as contest_rank
FROM sales_performance
WHERE month = '2024-01';
-- Result: If two people tie for 2nd place (both $45k sales),
-- they both get rank 2, and the next person gets rank 4
-- This is fair - no one gets "cheated" out of their true position
```
**RANK Use Cases:**
- ✅ **Sports competitions**: Olympic-style rankings
- ✅ **Sales contests**: Fair bonus tier assignments
- ✅ **Academic competitions**: Scholarship rankings
- ✅ **Performance reviews**: Employee ranking with meaningful ties
**DENSE_RANK() - The Category Organizer:**