Latest Order Per Customer In One Query

A page lists every customer with their most recent order. It currently runs one query for the customer list and then one more per customer. Return the whole thing in a single result set:

  • customer — the customer name
  • order_id — the id of their most recent order, or NULL if they have never ordered
  • placed_on — that order's date, or NULL
  • amount — that order's amount, or NULL

Every customer appears exactly once. Where a customer has two orders on the same date, the one with the higher id wins.

Order by customer.

Expected output


customer | order_id | placed_on  | amount
---------+----------+------------+--------
Acme     | 102      | 2024-05-20 | 150.00
Begal    | 104      | 2024-05-12 | 950.00
Corvus   | 106      | 2024-06-18 | 1200.00
Dynamo   | NULL     | NULL       | NULL
PostgreSQL

Press Run to start the SQL engine.

SensAI
Beta
Tap the mic to stop voice mode