runtime
35 / 88

lesson 35 Window functions · advanced

Window functions: ROW_NUMBER

Assign a sequence number to rows within a group.

the idea

Window functions calculate across related rows while keeping each row visible. ROW_NUMBER assigns 1, 2, 3 within a partition using its ORDER BY. Include a tie-breaker for repeatable results.

tables in this lesson

The challenges use this data. Each column shows its type underneath; → marks a link to another table.

orders6 columns · 12 rows
idinteger · keycustomer_idintegerproduct_idintegerquantityintegerstatustextordered_attext
101112paid2025-01-01
102231paid2025-01-02
103121paid2025-01-05
104352pending2025-01-08
105445paid2025-02-01

showing 5 of 12 rows

products4 columns · 6 rows
idinteger · keynametextcategorytextpricereal
1NotebookStationery12
2Desk lampHome45
3KeyboardTech80
4Pen setStationery8
5HeadphonesTech120

showing 5 of 6 rows

example

The idea in one query. Press Run to see what it returns; running examples never affects your progress.

example.sql
SELECT
  id,
  customer_id,
  ROW_NUMBER() OVER( PARTITION BY customer_id ORDER BY ordered_at, id ) AS order_number
FROM orders;

Watch for: The window ORDER BY controls calculation, not the final display order.

build it step by step

Each step changes one thing. Run them in order and watch the result change.

  1. Order a customer's orders. ROW_NUMBER needs a clear order within each partition. Sort one customer's orders by time to see the sequence.

    step-1.sql
    SELECT id, customer_id, ordered_at
    FROM orders
    WHERE customer_id = 1
    ORDER BY ordered_at, id;
  2. Number rows inside each partition. PARTITION BY customer_id restarts the counter for each customer. ORDER BY decides which row is 1, 2, 3…

    step-2.sql
    SELECT
      id,
      customer_id,
      ROW_NUMBER() OVER( PARTITION BY customer_id ORDER BY ordered_at, id ) AS order_seq
    FROM orders;

challenge 1

Return id, customer_id and order_number: number each customer's orders by ordered_at then id.

Return idcustomer_idorder_numberany row order

challenge-1.sql
 
To master this lesson, solve both challenges without hints and pass the concept check. 3 of 3 to go.