🎓 A1Learner
🔍
0 of 51 lessons completed

SQL Rank Functions

Rank functions hand out places in an order. Tied rows test them, because RANK, DENSE_RANK and ROW_NUMBER treat a tie in three different ways.

RANK on order quantities

Order 6 takes rank 1 with quantity 10. The five orders with quantity 1 share rank 6, after the skip.

SELECT order_id, quantity, RANK() OVER (ORDER BY quantity DESC) AS rank_num
FROM orders
ORDER BY quantity DESC, order_id;

DENSE_RANK on the same orders

The five orders with quantity 1 share rank 5 here, with no gap after the tie at rank 4.

SELECT order_id, quantity, DENSE_RANK() OVER (ORDER BY quantity DESC) AS dense_rank_num
FROM orders
ORDER BY quantity DESC, order_id;

All three side by side

ROW_NUMBER hands out 1 to 10 with no sharing. RANK and DENSE_RANK agree on the tied ranks and part ways after them.

SELECT order_id, quantity, ROW_NUMBER() OVER (ORDER BY quantity DESC) AS row_num, RANK() OVER (ORDER BY quantity DESC) AS rank_num, DENSE_RANK() OVER (ORDER BY quantity DESC) AS dense_rank_num
FROM orders
ORDER BY quantity DESC, order_id;

Example

SELECT name, price, RANK() OVER (ORDER BY price DESC) AS rank_num, ROW_NUMBER() OVER (ORDER BY price DESC) AS row_num
FROM products
ORDER BY price DESC;

Key points

  • RANK: a function that gives tied rows the same rank and then skips the next numbers
  • DENSE_RANK: a function that gives tied rows the same rank and never skips a number
  • ROW_NUMBER: a function that never shares a number, even on a tie
  • A tie means two rows hold the same value in the ORDER BY column.
  • The ORDER BY inside OVER sets the order the ranks follow.
  • Product prices in this shop are all different, so this lesson ranks order quantities instead.

In this example, the products are ranked from the dearest down. Every price differs from the rest, so no tie exists. RANK and ROW_NUMBER hand out the same numbers, 1 to 8, which shows a tie was never tested.

Try it Yourself

Edit the code, then press Run.

Running is simulated · DB Fiddle

Exercise

Five rows tie for second place. What rank does RANK give the next row?