Start learning free

LESSON 31 OF 66 · SQL: INTERVIEW QUESTIONS

Each Customer's First Order in Python

Practice

An interviewer asks: show each customer's first order, with its id and its total. The quick answer groups the orders by customer and takes MIN(ordered). That finds the right date, but the other columns are still worked out over the whole group. The starter's min_query shows it: Ana Pop's first order is worth 34, yet the total says 75, the sum of all her orders.

Number the rows, then keep the 1s: ROW_NUMBER() OVER (PARTITION BY … ORDER BY …) keeps every row and numbers the rows 1, 2, 3 inside each partition. A query can't filter its own window column in WHERE, so you number the rows in a CTE and keep the 1s in the main query. Here is the same idea on another question, each customer's latest order:

WITH latest AS (
    SELECT customer_id, id, ordered,
        ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY ordered DESC) AS n
    FROM orders
)
SELECT customer_id, id, ordered
FROM latest
WHERE n = 1

Your script prints min_query's rows first, then your query's: one row per customer, with the first order's id, its date and its own total:

name | first_order | total
Ana Pop | 2026-03-02 | 75
Ben Ortiz | 2026-03-15 | 38
Chloe Ng | 2026-04-18 | 89
Dan Weber | 2026-05-07 | 73
(4 rows)
name | order_id | ordered | total
Ana Pop | 1 | 2026-03-02 | 34
Ben Ortiz | 2 | 2026-03-15 | 29
Chloe Ng | 4 | 2026-04-18 | 27
Dan Weber | 5 | 2026-05-07 | 73
(4 rows)

Your task: the starter has min_query and the frame of WITH numbered AS ( … ), with its joins and GROUP BY orders.id, so each row is one order. Fill in numbered's SELECT (name, orders.id as order_id, ordered and the order's total) and its order_number column. Then read the rows from numbered and keep the ones numbered 1.


Assignment
Follow the Coding Tutorial to number each customer's orders inside numbered and keep the first one in the main query.


Hint
PARTITION BY customer_id starts the numbering again for each customer, and ORDER BY ordered gives 1 to the oldest order. The test order_number = 1 goes in the main query's WHERE.


STEP 1 OF 4
    Ctrl + Enter to check

    Sqlq First Order in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free