Learn SQL Lesson

Ranking Rows with ROW_NUMBER

Window functions are also great for ranking.

`ROW_NUMBER` gives each row a position inside its partition:

~~~sql SELECT region, salesperson, amount, ROW_NUMBER() OVER ( PARTITION BY region ORDER BY amount DESC ) AS region_row_number FROM sales_2 ~~~

This lets you answer questions like:

• What is the biggest sale in each region? • What are the top 3 orders per customer? • Which event happened first for each user?

`RANK` and `DENSE_RANK` are close relatives that handle ties differently, but `ROW_NUMBER` is the easiest place to start.

If two rows have the same sorting value, add a second column to make the order deterministic. For example, `ORDER BY amount DESC, id` breaks ties by `id`.

Practice challenge

Number the sales inside each region from largest amount to smallest. Return region, salesperson, amount, and region_row_number, ordered by region and region_row_number.

Open interactive editor