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 →Example
Giving every row its place
SELECT *, ROW_NUMBER() OVER (ORDER BY revenue DESC) AS revenue_rank
FROM orders| order_id | customer_id | revenue | revenue_rank |
|---|---|---|---|
| O2004 | C101 | 300.0 | 1 |
| O2002 | C102 | 210.0 | 2 |
| O2003 | C103 | 210.0 | 3 |
| O2001 | C101 | 150.0 | 4 |
Step by step
- 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 - 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 - 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
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 orders2. 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 employeesLearn 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 →