Chapter 7 · Lesson 4 of 6

Ranking Rows with ROW_NUMBER

Number rows inside each group with ROW_NUMBER() OVER (PARTITION BY ... ORDER BY ...) to rank sales from largest to smallest.

Window functions are also great for ranking.

ROW_NUMBER gives each row a position inside its partition:

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.

Sample data

This lesson loads the sales_2 table (16 rows) into DuckDB in your browser with one click, so you can run every example without uploading anything.

Setup SQL for sales_2
CREATE OR REPLACE TABLE sales_2 (
    id INTEGER,
    salesperson VARCHAR,
    region VARCHAR,
    amount DECIMAL(10,2),
    quantity INTEGER,
    sale_date DATE
  );

INSERT INTO sales_2 VALUES
    (1, 'Alice', 'West', 1200, 3, '2024-01-05'),
    (2, 'Bob', 'East', 850, 2, '2024-01-08'),
    (3, 'Alice', 'West', 640, 1, '2024-01-11'),
    (4, 'Diana', 'South', 430, 5, '2024-01-12'),
    (5, 'Eve', 'West', 1500, 4, '2024-02-01'),
    (6, 'Frank', 'East', 920, 2, '2024-02-03'),
    (7, 'Grace', 'North', 760, 2, '2024-02-07'),
    (8, 'Bob', 'East', 1100, 3, '2024-02-10'),
    (9, 'Alice', 'West', 780, 2, '2024-03-02'),
    (10, 'Bob', 'East', 990, 3, '2024-03-05'),
    (11, 'Diana', 'South', 610, 2, '2024-03-08'),
    (12, 'Eve', 'West', 700, 1, '2024-03-12'),
    (13, 'Frank', 'East', 1150, 4, '2024-03-15'),
    (14, 'Grace', 'North', 840, 2, '2024-03-18'),
    (15, 'Alice', 'West', 1320, 5, '2024-04-01'),
    (16, 'Bob', 'East', 730, 1, '2024-04-05');

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.

Hint: Use ROW_NUMBER() OVER (PARTITION BY region ORDER BY amount DESC, id).

Run your query in the editor and the lesson checks the result automatically.

Open this lesson in the SQL editor

Lessons in Window Functions

Calculate totals, running sums, rankings, and previous-row comparisons with OVER and PARTITION BY while keeping every detail row.

  1. 01 · OVER Keeps the Detail Rows
  2. 02 · PARTITION BY Creates Mini Windows
  3. 03 · Running Totals with ORDER BY
  4. 04 · Ranking Rows with ROW_NUMBER
  5. 05 · Looking Back with LAG
  6. 06 · Other Common Window Functions

Related guides