Find duplicates on a key column
The classic duplicate check: group by the column that should be unique and keep only the values that appear more than once.
The task
customers.email is supposed to be unique but was never given a unique constraint. You need the list of offending values before you can merge accounts or add the constraint.
The snippet
Runs unchanged on current versions of SQL Server, PostgreSQL, MySQL, SQLite and Oracle.
SELECT email, COUNT(*) AS occurrences
FROM customers
GROUP BY email
HAVING COUNT(*) > 1
ORDER BY occurrences DESC;
工作原理
GROUP BY email collects all rows sharing an address; HAVING filters down to values with more than one row and ORDER BY ranks the repeats. Swap email for any column that should be unique: a phone number, an SKU, an invoice number.
Variations
Show the full duplicate rows
WITH dupes AS (
SELECT email
FROM customers
GROUP BY email
HAVING COUNT(*) > 1
)
SELECT c.*
FROM customers c
JOIN dupes d ON d.email = c.email
ORDER BY c.email, c.id;
Duplicates on a composite key
SELECT order_id, product_id, COUNT(*) AS occurrences
FROM order_items
GROUP BY order_id, product_id
HAVING COUNT(*) > 1;
Questions that come up
How do I see which rows to keep and which to merge?
Join the duplicate values back to the table (first variant) and you get the full rows side by side. Each group of equal emails is a merge candidate: pick the survivor, point its children at it, and remove the rest. The delete-duplicates-keep-one recipe automates that for the common case.
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.