Subqueries and CTEs · Problem 65 of 118

Last Order Cancelled

HardSubqueries and CTEsShop data

Return customer_id and the cancelled order's order_id for every customer whose most recent order has the status 'cancelled'. Most recent means the greatest order_date, and for the same date the greatest order_id. Sort by customer_id. Only look at customers with customer_id from 1 to 40.

Hint 1

Find the latest order of each customer first, then keep those that are cancelled. Check the status of the latest order, not of any order.

Reference solution

SELECT o.customer_id, o.order_id
FROM orders AS o
WHERE o.customer_id BETWEEN 1 AND 40
  AND o.status = 'cancelled'
  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;

The order of the two ideas matters. "Customers whose latest order is cancelled" is not "cancelled orders": a customer with an old cancelled order and a newer delivered one must not appear. First identify each customer's latest order, then test that order's status. Putting the status test inside the WHERE together with the latest-order test does exactly this.