Keep only the latest update per customer
A customer_updates table gets a new row every time a customer changes their email: (update_id, customer_id, email, updated_at). Two updates for the same customer can share the same updated_at when they arrive in one batch.
Write a query that returns exactly one row per customer: the latest email. If two rows tie on updated_at, the higher update_id wins.
Think it through or sketch an answer first, then open the hint or the solution.
Show a hint
You need to number the rows inside each customer, newest first, with a tie-breaker, and keep row 1.
Show the solution
Use ROW_NUMBER() partitioned by customer and ordered newest first, with update_id as the tie-breaker, then keep row 1 in an outer query. ROW_NUMBER always gives distinct numbers, so each customer gets exactly one row even when timestamps tie.
Example (SQL)
WITH ranked AS (
SELECT customer_id, email, updated_at,
ROW_NUMBER() OVER (PARTITION BY customer_id
ORDER BY updated_at DESC, update_id DESC) AS rn
FROM customer_updates
)
SELECT customer_id, email, updated_at
FROM ranked
WHERE rn = 1;
Common mistakes
- Using GROUP BY customer_id with MAX(updated_at) and joining back: ties return two rows for the same customer.
- Using RANK() instead of ROW_NUMBER(): tied rows both get rank 1.
- Filtering on the window function in WHERE: window functions are computed after WHERE, so you need a subquery or CTE.
How did you do? Your answer is saved in this browser and comes back for revision later.