Mastering MySQL for Data AnalystsLesson 30 of 42
Lesson 30 of 42

Ranking Functions: ROW_NUMBER, RANK, DENSE_RANK & NTILE in MySQL 8.0

Overview & Learning Objectives

Ranking is one of the most common questions in data analytics: What are the top 3 best-selling products in each region? Who are the top 10% highest-spending customers? MySQL 8.0 provides four ranking window functions: `ROW_NUMBER()` (strictly unique sequential integers), `RANK()` (shares rank on ties and skips subsequent positions), `DENSE_RANK()` (shares rank on ties without skipping numbers), and `NTILE(n)` (buckets rows into n quantiles).

  • Master the critical distinctions between `ROW_NUMBER()`, `RANK()`, and `DENSE_RANK()` during ties.
  • Solve the classic "Top N per Category" business interview problem.
  • Segment customer databases into quartiles or deciles using `NTILE()`.
  • Deduplicate records cleanly using `ROW_NUMBER() OVER (...)`.

Industry Standard

Standard: Analytics engineering teams at Amazon and Flipkart use `ROW_NUMBER() OVER (PARTITION BY id ORDER BY updated_at DESC)` to deduplicate streaming clickstream records.

Real-World Example: ScoopCraft Dark-Store Product Sales Leaderboard

ScoopCraft ranks flavor sales within each store to isolate the top 2 best-sellers per location.

flavor_namedark_storerevenueROW_NUMBERRANKDENSE_RANK
Belgian ChocoKoramangala Hub₹50,000.00111
Mango SorbetKoramangala Hub₹35,000.0022 (Tie)2 (Tie)
Almond CrunchKoramangala Hub₹35,000.0032 (Tie)2 (Tie)
Vanilla BeanKoramangala Hub₹20,000.0044 (Skipped 3)3 (No gap)

Functions & Syntax Covered in this Chapter

Here is the definition, execution syntax, parameter breakdown, and real-world business example for each function/syntax covered in this chapter:

Feature 1

ROW_NUMBER()

Definition: Assigns a unique, consecutive integer starting from 1 to each row within a partition ordered by criteria. Ties receive distinct sequential numbers.

Syntax / Code Pattern:
ROW_NUMBER() OVER (PARTITION BY store_id ORDER BY sales DESC)
Parameters Breakdown:
  • PARTITION BY: Divides rows into groups.
  • ORDER BY: Determines the sequence in which numbers are assigned.
Real-World Example (Top 1 Product per Store):
Problem / Scenario: Assign a unique sequential rank to each product per store to pick the #1 best seller.
SQL Query / Expression: ROW_NUMBER() OVER (PARTITION BY store_id ORDER BY revenue DESC)
Result: 1, 2, 3, 4 (no duplicates even if revenues are identical)
Why it works: Guarantees strict 1-to-N numbering ideal for deduplication and Top-N filters.
Feature 2

RANK()

Definition: Assigns ranks where duplicate values receive identical rank numbers, with subsequent ranks skipping positions (1, 2, 2, 4).

Syntax / Code Pattern:
RANK() OVER (PARTITION BY region ORDER BY revenue DESC)
Parameters Breakdown:
  • ORDER BY: Columns evaluated for tied values.
Real-World Example (Store Revenue Leaderboard):
Problem / Scenario: Rank sales representatives where tied revenue shares the same prize rank.
SQL Query / Expression: RANK() OVER (ORDER BY sales DESC)
Result: 1, 2, 2, 4 (rank 3 is skipped after 2-way tie)
Why it works: Maintains Olympic-style ranking with position gaps.
Feature 3

DENSE_RANK()

Definition: Assigns ranks where duplicate values receive identical rank numbers, but subsequent ranks never skip positions (1, 2, 2, 3).

Syntax / Code Pattern:
DENSE_RANK() OVER (ORDER BY salary DESC)
Parameters Breakdown:
  • ORDER BY: Columns evaluated for tied values.
Real-World Example (Top 3 Distinct Sales Tiers):
Problem / Scenario: Find employees in the top 3 distinct commission tiers without missing tier ranks.
SQL Query / Expression: DENSE_RANK() OVER (ORDER BY commission DESC)
Result: 1, 2, 2, 3 (next tier is 3, no gap)
Why it works: Provides contiguous ranking sequence without holes.
Feature 4

NTILE(n)

Definition: Divides an ordered partition into n approximately equal buckets, assigning bucket numbers from 1 to n.

Syntax / Code Pattern:
NTILE(4) OVER (ORDER BY customer_spend DESC)
Parameters Breakdown:
  • n: Integer number of buckets (e.g. 4 for quartiles, 10 for deciles, 100 for percentiles).
Real-World Example (Customer RFM Spend Quartiles):
Problem / Scenario: Segment customers into 4 spend tiers (Quartile 1 = VIP whales, Quartile 4 = low spenders).
SQL Query / Expression: NTILE(4) OVER (ORDER BY lifetime_spend DESC)
Result: Bucket 1 (Top 25%), Bucket 2, Bucket 3, Bucket 4
Why it works: Evenly distributes ordered rows across 4 analytical quartiles.

Common Mistakes & Limitations

  • Using `RANK()` instead of `DENSE_RANK()` when seeking top 3 distinct metric tiers, accidentally missing tier 3 if a tie occurs at tier 2.
  • Forgetting the `ORDER BY` clause inside the `OVER()` specification of ranking functions, which makes rankings completely non-deterministic.

Keyboard Shortcuts (MySQL Workbench)

ActionWindowsMac
Execute QueryCtrl + EnterCmd + Enter

Pro Tips & Modern Best Practices

  • Use `ROW_NUMBER() OVER (PARTITION BY business_key ORDER BY modified_date DESC)` to pick the newest state for deduplication.
  • Combine `NTILE(10)` with customer lifetime spend to easily identify the top 10% (Decile 1) VIP whales.