Latest order per customer
Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.
For each customer, return their most recent order: the columns customer_id, order_id, order_date and amount.
If a customer placed several orders on their latest date, return the one with the highest id. Exactly one row per customer. Rows can be returned in any order.
Example
orders
| id | customer_id | order_date | amount |
|---|---|---|---|
| 1 | 10 | 2024-03-01 | 120.00 |
| 2 | 20 | 2024-03-02 | 35.50 |
| 3 | 10 | 2024-03-15 | 80.00 |
| 4 | 20 | 2024-02-20 | 99.90 |
| 5 | 30 | 2024-01-05 | 15.00 |
Result:
| customer_id | order_id | order_date | amount |
|---|---|---|---|
| 10 | 3 | 2024-03-15 | 80.00 |
| 20 | 2 | 2024-03-02 | 35.50 |
| 30 | 5 | 2024-01-05 | 15.00 |
Tip
MAX(order_date) tells you when, but the other columns of that row are lost in the GROUP BY. Number the rows inside each customer instead.
Schema
CREATE TABLE orders (
id INT PRIMARY KEY,
customer_id INT NOT NULL,
order_date DATE NOT NULL,
amount NUMERIC(10, 2) NOT NULL
);Approach
This is the greatest-n-per-group pattern, probably the most common SQL question in interviews. Number each customer's orders from newest to oldest and keep number 1:
SELECT customer_id, order_id, order_date, amount
FROM (
SELECT
customer_id,
id AS order_id,
order_date,
amount,
ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date DESC, id DESC) AS rn
FROM orders
) ranked
WHERE rn = 1;id DESC is the tie-breaker. Without it, two orders on the same date get numbered in an arbitrary order and the result can change between runs. Here we want exactly one row, so it's ROW_NUMBER and not RANK.
Postgres: DISTINCT ON
Postgres has a shorter way to say "the first row of each group":
SELECT DISTINCT ON (customer_id)
customer_id, id AS order_id, order_date, amount
FROM orders
ORDER BY customer_id, order_date DESC, id DESC;The ORDER BY must start with the DISTINCT ON columns. It's concise but Postgres-only, so mention that the ROW_NUMBER version is portable.
Why MAX + join is not enough
Joining back on (customer_id, MAX(order_date)) returns both orders when there are two on the last date. You would need a second step to break the tie.
Performance
An index on (customer_id, order_date DESC, id DESC) lets Postgres read each customer's newest order straight from the index.
Reference solution
SELECT customer_id, order_id, order_date, amount
FROM (
SELECT
customer_id,
id AS order_id,
order_date,
amount,
ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date DESC, id DESC) AS rn
FROM orders
) ranked
WHERE rn = 1;