Skip to content
GreenSnippets

Find duplicate rows by one or more columns

List values that appear more than once with GROUP BY and HAVING, including how many times.

SQL
SELECT lower(email) AS email, COUNT(*) AS occurrences
FROM users
GROUP BY lower(email)
HAVING COUNT(*) > 1
ORDER BY occurrences DESC, email;

Example / expected output

Output
email         | occurrences
---------------+-------------
 ann@x.test    |           3
 bob@x.test    |           2

How it works

GROUP BY the columns that define a duplicate, then keep only groups with HAVING COUNT(*) > 1. Lowercase text columns first (lower(email)) if case differences should count as duplicates.

Once you have found duplicates, add a unique index so they cannot come back.