Keep the newest row per key
Partition by the key, order by recency descending, and keep rank 1: one row per key, the most recent one.
The task
addresses accumulates a row per change, so a customer has many. Reports want the current address: exactly one row per customer, the one with the latest updated_at.
The snippet
Runs unchanged on current versions of SQL Server, PostgreSQL, MySQL, SQLite and Oracle.
WITH ranked AS (
SELECT id, customer_id, city, updated_at,
ROW_NUMBER() OVER (
PARTITION BY customer_id
ORDER BY updated_at DESC, id DESC
) AS rn
FROM addresses
)
SELECT id, customer_id, city, updated_at
FROM ranked
WHERE rn = 1;
작동 방식
Each customer_id partition is ordered newest-first, so rn = 1 is the latest address; the id DESC tiebreaker makes the winner deterministic when two rows share a timestamp. The WHERE keeps only the winners, one row per customer. History stays in the table; this is a view over it, not a delete.
Variations
Physically keep only the newest (delete the rest)
DELETE FROM addresses
WHERE id IN (
SELECT id
FROM (
SELECT id,
ROW_NUMBER() OVER (
PARTITION BY customer_id
ORDER BY updated_at DESC, id DESC
) AS rn
FROM addresses
) ranked
WHERE rn > 1
);
Questions that come up
Latest by updated_at or by id?
By a real timestamp when you have one you trust; by id when you do not, because auto-increment ids reflect insert order. Ordering by both (timestamp first, id as tiebreaker) handles equal timestamps deterministically. Never trust a timestamp that application code forgets to set; check the rows-changed-since-yesterday recipe for that audit.
Keep reading
Run these with autocomplete that knows your tables
SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.