IntermediateDeduplication

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_idemailupdated_at
1asha@old.com2026-01-05
1asha@new.com2026-02-10
2ben@mail.com2026-01-20
3chen@a.com2026-01-02
3chen@b.com2026-03-01
3chen@c.com2026-02-14
Expected output
customer_idemailupdated_at
1asha@new.com2026-02-10
2ben@mail.com2026-01-20
3chen@b.com2026-03-01
Show solution
SQL
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.

The full explanation, with more examples, is in the question Keep the latest row per customer.