RANK — Complete Guide
RANK — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of MySQL Tutorial on Toolliyo Academy.
On this page
MySQL Tutorial · Lesson 37 of 100
RANK
Basics ✓ → Advanced
Advanced · 2 — Production · ~6 min · MySQL — Functions & Window Functions
What is this?
RANK() assigns competition ranking with gaps: tied values share rank, next rank skips (1,1,3). Useful for leaderboards where ties matter.
Why should you care?
Top sellers board showing two #1 stores then #3 (no #2) matches how sports rankings behave.
See it live — copy this example
Run in MySQL Workbench or the mysql CLI.
SELECT p.sku,
SUM(oi.qty) AS units_sold,
RANK() OVER (ORDER BY SUM(oi.qty) DESC) AS sales_rank
FROM order_items oi
JOIN products p ON p.product_id = oi.product_id
GROUP BY p.product_id, p.sku;
What happened?
- Products grouped by total qty sold.
- RANK orders by units; ties get same rank and gap follows.
- Different from ROW_NUMBER which breaks ties arbitrarily.
Practice next
- Seed order_items so two SKUs tie qty.
- Run query; observe shared rank and gap.
- Swap RANK for ROW_NUMBER — compare tie handling.
- RANK() OVER (PARTITION BY category ORDER BY SUM(qty) DESC) if category exists.
- Filter WHERE sales_rank <= 10.
Remember
RANK allows ties and gaps. Good for public leaderboards. Pair with ORDER BY on metric DESC.
DataFlow bestseller board
Admin UI shows SKUs with tied ranks during flash sale.
Outcome: Merchants see fair tie display without fake ordering.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!