Dedupe with window functions
ROW_NUMBER over a partition of the duplicate key numbers the copies; the outer query keeps rank 1 and shows the rest.
The task
The general-purpose dedupe: number the copies within each key, decide the keep rule in the ORDER BY, and filter. It previews as easily as it deletes.
The snippet
Runs unchanged on current versions of SQL Server, PostgreSQL, MySQL, SQLite and Oracle.
WITH ranked AS (
SELECT id, email, name, created_at,
ROW_NUMBER() OVER (
PARTITION BY email
ORDER BY created_at ASC, id ASC
) AS rn
FROM customers
WHERE email IS NOT NULL
)
SELECT id, email, name, created_at, rn
FROM ranked
WHERE rn > 1
ORDER BY email, rn;
Cómo funciona
PARTITION BY email starts the numbering fresh for each address; ORDER BY created_at, id decides which copy ranks first; change that ORDER BY and you change the keep rule, nothing else. rn > 1 lists every losing copy; switch to rn = 1 to preview the survivors. Rows with no email are filtered out first, or they would all share one partition and be treated as copies of each other. The DELETE variant reuses the same ranking inside a derived table, the form Oracle and MySQL accept.
Variations
The delete, reusing the same ranking
DELETE FROM customers
WHERE id IN (
SELECT id
FROM (
SELECT id,
ROW_NUMBER() OVER (
PARTITION BY email
ORDER BY created_at ASC, id ASC
) AS rn
FROM customers
WHERE email IS NOT NULL
) ranked
WHERE rn > 1
);
DENSE_RANK keeps every tied row (largest order per customer)
WITH ranked AS (
SELECT id, customer_id, total,
DENSE_RANK() OVER (
PARTITION BY customer_id
ORDER BY total DESC
) AS rnk
FROM orders
)
SELECT id, customer_id, total
FROM ranked
WHERE rnk = 1;
Questions that come up
ROW_NUMBER, RANK or DENSE_RANK for dedupe?
ROW_NUMBER gives every copy a distinct number, so exactly one row survives per partition, which is what dedupe usually wants. RANK and DENSE_RANK give tied rows the same rank, so a tie can keep several rows and delete none. Use ROW_NUMBER with a tiebreaker (id) in the ORDER BY to make the survivor deterministic.
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.