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 nameorder_id— the id of their most recent order, orNULLif they have never orderedplaced_on— that order's date, orNULLamount— that order's amount, orNULL
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
Editorial
The query being replaced looks like this in application code:
customers = query("SELECT id, name FROM customer")
for c in customers:
latest = query("SELECT * FROM \"order\" WHERE customer_id = ? "
"ORDER BY placed_on DESC, id DESC LIMIT 1", c.id)
Four customers, five queries. Four thousand customers, four thousand and one queries. 💡 N+1 = one query to get a list, then one more per item in it. Each one is fast, and the page is slow because the round trips add up.
The rewrite
WITH ranked AS (
SELECT o.*,
row_number() OVER (PARTITION BY o.customer_id
ORDER BY o.placed_on DESC, o.id DESC) AS rn
FROM "order" o
)
SELECT c.name AS customer, r.id AS order_id, r.placed_on, r.amount
FROM customer c
LEFT JOIN ranked r ON r.customer_id = c.id AND r.rn = 1
ORDER BY c.name;
row_number() numbers each customer's orders newest first, and
rn = 1 keeps the newest. PARTITION BY is what makes
the numbering restart per customer rather than running 1..6 across the whole
table.
The predicate belongs in the ON clause
Moving r.rn = 1 into a WHERE clause breaks it:
-- WRONG: Dynamo disappears
FROM customer c
LEFT JOIN ranked r ON r.customer_id = c.id
WHERE r.rn = 1
The LEFT JOIN gives Dynamo one row with every
r column NULL, and NULL = 1 is unknown, so the
WHERE discards it. A WHERE clause on the nullable side
of an outer join turns it back into an inner join. The condition has to be part
of the join, where it decides what matches, not part of the filter,
where it decides what survives.
The tie is why max() is not enough
-- WRONG: Begal comes back twice
SELECT c.name, o.id, o.placed_on, o.amount
FROM customer c
LEFT JOIN "order" o ON o.customer_id = c.id
WHERE o.placed_on = (SELECT max(placed_on) FROM "order" WHERE customer_id = c.id)
Begal has two orders on 2024-05-12, and both equal the maximum. "The latest order" is only well defined once something breaks the tie, which is why the statement names the higher id. Any top-N-per-group answer needs a total order, and a date alone is almost never one.
DISTINCT ON, the PostgreSQL shortcut
SELECT DISTINCT ON (o.customer_id)
o.customer_id, o.id, o.placed_on, o.amount
FROM "order" o
ORDER BY o.customer_id, o.placed_on DESC, o.id DESC;
Shorter and usually faster: it keeps the first row of each
customer_id group as the ORDER BY presents them. Two
catches. The leading ORDER BY columns must match the
DISTINCT ON columns exactly, and it is PostgreSQL-only — no MySQL,
no SQL Server. It also gives you no way to attach customers with no orders, so
reaching the stated answer still needs this as a subquery with a
LEFT JOIN around it.
LATERAL, when you want more than one
SELECT c.name AS customer, r.id AS order_id, r.placed_on, r.amount
FROM customer c
LEFT JOIN LATERAL (
SELECT o.id, o.placed_on, o.amount
FROM "order" o
WHERE o.customer_id = c.id
ORDER BY o.placed_on DESC, o.id DESC
LIMIT 1
) r ON true
ORDER BY c.name;
💡 LATERAL = a subquery in the FROM clause that may reference columns
from the tables to its left. It is the per-customer LIMIT 1
from the application loop, moved inside the database, and it is the closest
thing to "run that query for each row" that one statement can express. Change
LIMIT 1 to LIMIT 3 and you have the three most recent
orders per customer, which the rn = 1 version gets by changing the
filter to rn <= 3 and DISTINCT ON cannot do at
all.
With an index on (customer_id, placed_on DESC, id DESC), the
LATERAL form is often the fastest of the three, because each of the N
executions is an index seek plus one row rather than a scan — the planner does
the loop, but with no network round trip per iteration, which is where the N+1
cost actually lived.
What an interviewer is checking
That you can name the pattern, and that you know the fix is one query rather than a cache. The follow-up is usually "what if the list is paginated" — and the answer is that you batch within the page, so a page of 50 customers is two queries, not 51.
customer
4 rows
| idinteger | nametext |
|---|---|
| 1 | Acme |
| 2 | Begal |
| 3 | Corvus |
| 4 | Dynamo |
order
6 rows
| idinteger | customer_idinteger | placed_ondate | amountnumeric(10,2) |
|---|---|---|---|
| 101 | 1 | 1709251200000000 | 400 |
| 102 | 1 | 1716163200000000 | 150 |
| 103 | 2 | 1715472000000000 | 900 |
| 104 | 2 | 1715472000000000 | 950 |
| 105 | 2 | 1704585600000000 | 75 |
Showing 5 of 6 rows.