RANK
ranking rows with gaps for ties.
This topic uses window functions or CTEs; MySQL requires version 8.0 or later.
Overview
RANK is a window ranking function: equal sort values receive the same rank and the following rank skips occupied positions, such as 1, 1, 3. It does not collapse rows, and PARTITION BY can restart ranking per group. When ties need deterministic treatment, decide whether the business requires shared ranks or ROW_NUMBER instead.
Basic syntax
SELECT name, RANK() OVER (ORDER BY amount DESC) AS rnk FROM orders;
Examples
RANK example
Rank orders by amount descending and observe how equal amounts share a rank and leave a gap afterward.
Sample table
orders| name | amount |
|---|---|
| Alice | 1200 |
| Bob | 900 |
| Cindy | 1500 |
| David | 700 |
Run result
| name | rnk |
|---|---|
| Cindy | 1 |
| Alice | 2 |
| Bob | 3 |
| David | 4 |
Common issues
No. They keep detail rows while calculating ranks, neighboring values, or running results.
When window sort values tie, add a stable unique tie-breaker.
No. Add a query-level ORDER BY to guarantee the final output order.
Tags
Was this explanation clear?
Thanks. This feedback will inform the next content review.