Latest Order, the Window Way
For customers 1 to 6, return customer_id, order_id and order_date of the customer's most recent order (the greatest order_date; for the same date, the greatest order_id). Sort by customer_id.
Hint 1
Number each customer's orders from the newest with ROW_NUMBER(), in a CTE or subquery.
Hint 2
A window function cannot be used in WHERE: filter on the number in the outer query.
Reference solution
WITH numbered AS (
SELECT customer_id, order_id, order_date,
ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date DESC, order_id DESC) AS n
FROM orders
WHERE customer_id BETWEEN 1 AND 6
)
SELECT customer_id, order_id, order_date
FROM numbered
WHERE n = 1
ORDER BY customer_id;
This is the number, then filter pattern: ROW_NUMBER() gives 1, 2, 3, ... inside each customer in the order you choose; keeping n = 1 keeps one row per customer. Compare with the correlated subquery of the previous chapter: the window version reads the table once, and n <= 3 would give the three latest orders with no other change. Window functions are only allowed in the SELECT list and ORDER BY, which is why the filter needs the outer query.