Skip to main content
06

Latest order per customer

Mediumgreatest-n-per-groupROW_NUMBERDISTINCT ON

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

idcustomer_idorder_dateamount
1102024-03-01120.00
2202024-03-0235.50
3102024-03-1580.00
4202024-02-2099.90
5302024-01-0515.00

Result:

customer_idorder_idorder_dateamount
1032024-03-1580.00
2022024-03-0235.50
3052024-01-0515.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

sql
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:

sql
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":

sql
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

sql
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;