Find duplicate emails ignoring case
Lowercase the column before grouping to catch duplicates that differ only in letter case, then aggregate the raw variants.
The task
Emails are case-insensitive in practice, but the column stored them as typed. Support reports 'the same customer twice' that the exact-match duplicate check cannot see.
The snippet
Written for PostgreSQL. Versions for MySQL are under Variations.
SELECT LOWER(email) AS email_key, COUNT(*) AS occurrences,
STRING_AGG(email, ', ' ORDER BY email) AS stored_variants
FROM customers
WHERE email IS NOT NULL
GROUP BY LOWER(email)
HAVING COUNT(*) > 1
ORDER BY occurrences DESC;
仕組み
LOWER(email) is the grouping key, so '[email protected]' and '[email protected]' join one group. HAVING keeps groups with more than one row. STRING_AGG lists the stored spellings side by side: the raw evidence you need when merging accounts.
Variations
MySQL: GROUP_CONCAT
MySQLSELECT LOWER(email) AS email_key, COUNT(*) AS occurrences,
GROUP_CONCAT(email SEPARATOR ', ') AS stored_variants
FROM customers
WHERE email IS NOT NULL
GROUP BY LOWER(email)
HAVING COUNT(*) > 1;
Trim and lowercase together
SELECT LOWER(TRIM(email)) AS email_key, COUNT(*) AS occurrences
FROM customers
WHERE email IS NOT NULL
GROUP BY LOWER(TRIM(email))
HAVING COUNT(*) > 1;
Questions that come up
Should I just add a case-insensitive unique index?
That is the durable fix: a unique index on LOWER(email) on PostgreSQL, Oracle, SQLite and MySQL 8.0.13+, or a citext column on PostgreSQL. On SQL Server and MySQL a plain unique index already ignores case under the default case-insensitive collations. The audit query still comes first: existing duplicates make CREATE UNIQUE INDEX fail, so merge them before you create it.
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.