Subqueries and CTEs · Problem 61 of 118

Latest Order of Each Customer

MediumSubqueries and CTEsShop data

For customers 1 to 6, return customer_id, order_id and order_date of the customer's most recent order. If a customer has two orders on the latest date, take the one with the higher order_id. Sort by customer_id.

Hint 1

For each order, ask: "is this the customer's latest one?" A correlated subquery can compute the latest (order_date, order_id) for that customer.

Hint 2

ORDER BY order_date DESC, order_id DESC LIMIT 1 inside the subquery picks one id.

Reference solution

SELECT o.customer_id, o.order_id, o.order_date
FROM orders AS o
WHERE o.customer_id BETWEEN 1 AND 6
  AND o.order_id = (
    SELECT o2.order_id
    FROM orders AS o2
    WHERE o2.customer_id = o.customer_id
    ORDER BY o2.order_date DESC, o2.order_id DESC
    LIMIT 1
  )
ORDER BY o.customer_id;

A correlated subquery refers to the outer row (o.customer_id), so it is evaluated once per outer row. The "latest per group" pattern is everywhere in real work: latest status, latest price, latest login. Comparing with MAX(order_date) returns all rows that share the date; ordering by date and id and taking LIMIT 1 guarantees one row per customer. (In the window functions chapter you will meet ROW_NUMBER(), the more scalable version of the same idea.)