14. Latest order per customer
Asked in screens shaped like: Shopify, Square, Instacart
Build a one-row-per-customer table holding their most recent order. Two orders can share a timestamp, so the tie-break has to be deterministic or your pipeline produces different rows on every run.
Requirements
- Columns: customer_id, order_id, ordered_at
- Exactly one row per customer_id
- Latest by ordered_at; ties broken by the lowest order_id
- Order by customer_id
Expected output
customer_id, order_id, ordered_at
Row order is graded, so ORDER BY matters here.
Tables this problem reads. The full warehouse is available in thesandbox.
orders
~200 rows
Order headers. One row per order, so amount is the order total — not a line total.
- order_idINTEGER— 1000–1199
- customer_idTEXT— C01–C12
- countryTEXT— US, DE, IN, UK, BR
- amountREAL
- statusTEXT— 'completed' or 'cancelled'
- ordered_atTEXT— YYYY-MM-DD HH:MM:SS
Pick a warehouse dialect above the editor. The engine is still SQLite; common syntax is rewritten before it runs.
SQLite cheat sheet
- Truncate to day
DATE(ordered_at) - Current date
DATE('now') - Conditional
CASE WHEN … THEN … ELSE … END - String aggregate
GROUP_CONCAT(col, ", ") - JSON field
json_extract(payload, '$.source') - Date difference
JULIANDAY(a) - JULIANDAY(b) - Filter a window
CTE, then WHERE rn = 1 - Median
ROW_NUMBER + COUNT(*) OVER ()
Revealed one at a time. The reference query stays in the Solution tab.
Hint 1
ROW_NUMBER() with PARTITION BY customer_id gives each customer their own counter.
Hint 2
You cannot filter a window function in WHERE — wrap it in a CTE first.
Hint 3
ORDER BY ordered_at DESC, order_id ASC inside the OVER clause, then keep rn = 1.
WITH ranked AS (
SELECT customer_id, order_id, ordered_at,
ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY ordered_at DESC, order_id ASC) AS rn
FROM orders
)
SELECT customer_id, order_id, ordered_at
FROM ranked
WHERE rn = 1
ORDER BY customer_id;Why it works
ROW_NUMBER guarantees one row per partition. RANK would return both rows on a tie and break the one-row-per-customer contract, which is why the secondary sort key matters.
Run your query to see the result set.
Submit to run the checks.
Why it works
ROW_NUMBER guarantees one row per partition. RANK would return both rows on a tie and break the one-row-per-customer contract, which is why the secondary sort key matters.
Pro problem
Medium problems unlock with Pro
Easy pads stay free. Medium and hard SQL and Python problems — editor, tests, hints, and solutions — open after you upgrade to Pro or coaching.
See plansPractice free easy problems