Querydrill

Level 4: Advanced Exercise 92 of 161 Medium Ranking and top N per group

Latest order per customer (DISTINCT ON)

An SQL exercise from Querydrill. Solve it with a SQL editor in your browser, checked on the rows it returns and again on changed data, and it is checked the moment you submit.

Try it yourself

For each customer, return the customer_id, the id and the amount of their most recent order (latest date, then highest id), whatever the status.

orders (first 12 of 14 rows)

idcustomer_idorder_dateamountstatus
10112025-01-03120paid
10212025-01-2080.5paid
10322025-01-22200paid
10432025-02-0245refunded
10532025-02-15310paid
10642025-02-18150pending
10752025-03-0160paid
10862025-03-0995paid
10962025-03-30130paid
11062025-04-1175paid
11172025-04-12210paid
11212025-04-2540paid

Free, no account needed. PostgreSQL runs in your browser and your answer is checked again on changed data.

What this exercise teaches

DISTINCT ON is PostgreSQL's short form of the row per group pattern: the ORDER BY must start with the grouping column, and what follows decides which row of the group survives. ROW_NUMBER with a filter on 1 does the same in any database.

A hint if you get stuck

DISTINCT ON (column) keeps the first row of each group in the ORDER BY you give.

Background you need

Common mistakes on this exercise

  • Sorted ascending: returns the first order, not the latest.
  • The highest id and the highest amount can come from different orders.

Each of these returns a result that looks plausible. The checker catches them because it runs your query on changed data as well.

Keep going on the practice page

Your first 8 exercises on Querydrill are free, with no account. The practice page has the full editor, timed mode and all the exercises in order. A free account shows 3 reference solutions a day; Pro unlocks every exercise, every solution, timed mode and the certificate.

Open this exercise

More exercises in Advanced