SQL Practice Logo

SQLPractice Online

Ranking Functions Deep Dive: Concept

Module: Window Functions

Ranking functions are like judges in different types of competitions. ROW_NUMBER is like assigning unique bib numbers to marathon runners - everyone gets a different number, even if they finish at exactly the same time. RANK is like Olympic scoring - tied athletes get the same rank, but the next rank skips numbers (gold, silver, silver, bronze becomes 1st, 2nd, 2nd, 4th). DENSE_RANK is like academic grades - tied students get the same rank, but the next rank continues sequentially (A, B, B, C becomes 1st, 2nd, 2nd, 3rd). Choose based on your business logic: unique identifiers, competition rules, or continuous categories.

**

**ROW_NUMBER() - The Unique Identifier:**

ROW_NUMBER assigns a unique sequential number to every row, regardless of ties. It's deterministic within the same session but arbitrary for tied values.

```sql

-- E-commerce product pagination

SELECT product_id, product_name, price,

ROW_NUMBER() OVER(ORDER BY price DESC) as page_position

FROM products

WHERE category = 'Electronics';

-- Result: Perfect for "Show items 21-40" pagination

-- Even if 5 products have same price, each gets unique position

```

**When to use ROW_NUMBER:**

- ✅ Pagination systems (OFFSET/LIMIT alternative)

- ✅ Unique record identification

- ✅ Breaking ties arbitrarily

- ✅ Sampling (every Nth record)

**RANK() - The Competition Scorer:**

RANK gives tied values the same rank but skips subsequent ranks. If two people tie for 2nd place, the next person is ranked 4th (no 3rd place).

```sql

-- Sales leaderboard with proper tie handling

SELECT salesperson_name, total_sales,

RANK() OVER(ORDER BY total_sales DESC) as sales_rank

FROM monthly_sales

WHERE month = '2024-01';

-- Result:

-- Alice: $50k (Rank 1)

-- Bob: $40k (Rank 2)

-- Carol: $40k (Rank 2) -- Tied for 2nd

-- Dave: $30k (Rank 4) -- Next rank skips 3

```

**When to use RANK:**

- ✅ Sports competitions and leaderboards

- ✅ Performance rankings with meaningful ties

- ✅ Academic or contest scoring

- ✅ When gaps after ties make business sense

**DENSE_RANK() - The Category Organizer:**

DENSE_RANK gives tied values the same rank but continues sequentially (no gaps). Perfect when you need continuous ranking levels.

```sql