BBampaa

Lessons › SQL › Chapter 6: Window Functions

SQL lesson

ROW_NUMBER() / RANK() / DENSE_RANK()

A ranking gives each row a place: 1st, 2nd, 3rd. Unlike GROUP BY, every row stays. You just get a new column with its place. There are three ways to rank, and they only differ when two rows tie: ROW_NUMBER always counts 1, 2, 3. RANK gives ties the same place, then skips (1, 2, 2, 4). DENSE_RANK gives ties the same place without skipping (1, 2, 2, 3).

Try this lesson free →
About 5–10 minutes · no sign-up needed

Example

Giving every row its place

SELECT *, ROW_NUMBER() OVER (ORDER BY revenue DESC) AS revenue_rank
FROM orders

Result:

order_idcustomer_idrevenuerevenue_rank
O2004C101300.01
O2002C102210.02
O2003C103210.03
O2001C101150.04

Step by step

  1. A new number for every row, even when two tie. Use it when every row needs its own number.
    SELECT *, ROW_NUMBER() OVER (ORDER BY revenue DESC) AS revenue_rank FROM orders
  2. Ties share a place, then the next place is skipped. Like a race: two silver medals, no bronze.
    SELECT *, RANK() OVER (ORDER BY revenue DESC) AS revenue_rank FROM orders
  3. Ties share a place, and the next place follows on. Use it for 'top 3 prices', where a tie shouldn't push a price out.
    SELECT *, DENSE_RANK() OVER (ORDER BY revenue DESC) AS revenue_rank FROM orders

Practice

Try each one in your head first, then open the answer.

1. Using orders, show every order with its place by revenue, biggest first. Name it revenue_rank.
SELECT *, ROW_NUMBER() OVER (ORDER BY revenue DESC) AS revenue_rank FROM orders
2. Using employees, number every employee by salary, highest first, one number each. Name it row_num.
SELECT *, ROW_NUMBER() OVER (ORDER BY salary DESC) AS row_num FROM employees

Learn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.

Try this lesson free →
About 5–10 minutes · no sign-up needed