// SQL snippet

Keep the oldest row per key

Partition by the key, order by creation ascending, and keep rank 1: one row per key, the one that was created first.

Main statement
All engines

The task

Merge tooling often wants the original record to survive: the account that was created first, with every later duplicate retired toward it. Ranking ascending picks the originals.

The snippet

Runs unchanged on current versions of SQL Server, PostgreSQL, MySQL, SQLite and Oracle.

All engines
WITH ranked AS (
  SELECT id, customer_id, city, created_at,
         ROW_NUMBER() OVER (
           PARTITION BY customer_id
           ORDER BY created_at ASC, id ASC
         ) AS rn
  FROM addresses
)
SELECT id, customer_id, city, created_at
FROM ranked
WHERE rn = 1;

它的運作方式

Ordering each partition by created_at ASC puts the original first, so rn = 1 is the oldest row per customer; id ASC breaks creation-time ties deterministically. WHERE rn = 1 keeps exactly one row per key. This is the mirror image of keep-newest-per-key: same shape, opposite sort.

Variations

Delete everything but the originals

DELETE FROM addresses
WHERE id IN (
  SELECT id
  FROM (
    SELECT id,
           ROW_NUMBER() OVER (
             PARTITION BY customer_id
             ORDER BY created_at ASC, id ASC
           ) AS rn
    FROM addresses
  ) ranked
  WHERE rn > 1
);

Oldest per key with MIN + join (no window functions)

SELECT a.*
FROM addresses a
JOIN (
  SELECT customer_id, MIN(created_at) AS first_created
  FROM addresses
  GROUP BY customer_id
) f ON f.customer_id = a.customer_id
   AND f.first_created = a.created_at
ORDER BY a.customer_id;

Questions that come up

Why prefer the window version over MIN + join?

Both find the oldest row, but the window version returns exactly one row per key even when several share the same created_at, while MIN + join returns all tied rows. When 'exactly one survivor per key' matters (merges, deletes, unique indexes), ROW_NUMBER with an id tiebreaker is the safer shape.

Keep reading

// snippets are better with a schema brain

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.