SQL reference

RANK, DENSE_RANK and ROW_NUMBER in SQL

In Excel, you'd reach for
fx=RANK.EQ(), or sorting and numbering 1, 2, 3 down the column

Three ways to number rows in order, which differ only on ties:

  • ROW_NUMBER(): 1, 2, 3, 4. Ties get different numbers (arbitrarily, unless you add a tie-breaker).
  • RANK(): 1, 2, 2, 4. Ties share a rank, then it skips. Like Excel's RANK.EQ.
  • DENSE_RANK(): 1, 2, 2, 3. Ties share, no gaps.

Syntax

RANK() OVER (PARTITION BY group_col ORDER BY score DESC)
Try itEdit the query, then Run
agentclosedrow_numberrankdense_rank
Emma113111
Chloe100222
Asha99333
Bruno94444
Diego83555

5 rows

Add PARTITION BY to rank within groups (best product per region, top customer per country), then filter on the rank in an outer query. That's the top N per group recipe.

Your turn

Rank customers by number of orders, most first: customer_id, orders and order_rank using DENSE_RANK. Keep only the top 3 ranks.

This page on one card

RANK, DENSE_RANK and ROW_NUMBER in SQL: the Excel way (=RANK.EQ()) and the SQL query, side by side
RANK, DENSE_RANK and ROW_NUMBER in SQL, on one card: the Excel way and the SQL. Download · Save to Pinterest
The practice data (7 tables)

See every column and sample rows