Keep the latest row per customer
Task
customer_updates has several versions of some customers. Return only the latest version of each customer_id (largest updated_at). Columns: customer_id, email, updated_at.
Row order does not matter. Column names do not have to match. SQLite dialect.
Tables
customer_updates
customer_id INTEGER, email TEXT, updated_at TEXT
| customer_id | updated_at | |
|---|---|---|
| 1 | asha@old.com | 2026-01-05 |
| 1 | asha@new.com | 2026-02-10 |
| 2 | ben@mail.com | 2026-01-20 |
| 3 | chen@a.com | 2026-01-02 |
| 3 | chen@b.com | 2026-03-01 |
| 3 | chen@c.com | 2026-02-14 |
- Number the versions of each customer, newest first.
- ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY updated_at DESC), then keep rn = 1.
Expected output
| customer_id | updated_at | |
|---|---|---|
| 1 | asha@new.com | 2026-02-10 |
| 2 | ben@mail.com | 2026-01-20 |
| 3 | chen@b.com | 2026-03-01 |
Show solution
SELECT customer_id, email, updated_at
FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY updated_at DESC) AS rn
FROM customer_updates
)
WHERE rn = 1;MAX(updated_at) with MAX(email) mixes values from different rows. Ranking whole rows with ROW_NUMBER keeps each row's columns together. Here ties on updated_at cannot happen; in real data add a tie-breaker.
Why this works
MAX(updated_at) with MAX(email) mixes values from different rows. Ranking whole rows with ROW_NUMBER keeps each row's columns together. Here ties on updated_at cannot happen; in real data add a tie-breaker.
The full explanation, with more examples, is in the question Keep the latest row per customer.