// SQL snippet

Find duplicates hiding behind whitespace

Trim the suspect column before grouping so '[email protected]' and '[email protected] ' land in the same group and reveal as duplicates.

Main statement
All engines

The task

find-duplicates-on-a-key reports no duplicate emails, yet support swears customers are double. Leading or trailing spaces (often from copy-paste) can make identical values look distinct.

The snippet

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

All engines
SELECT TRIM(email) AS cleaned_email, COUNT(*) AS occurrences,
       MIN(email) AS stored_example
FROM customers
WHERE email IS NOT NULL
GROUP BY TRIM(email)
HAVING COUNT(*) > 1
ORDER BY occurrences DESC;

仕組み

TRIM strips leading and trailing spaces from each email before grouping, so values that differ only by whitespace collapse together. HAVING keeps the collapsed groups with more than one row; MIN(email) shows one raw example of how the values look in storage. TRIM needs SQL Server 2017 or later. SQL Server also compares strings as if the shorter one were padded with spaces, so '[email protected]' = '[email protected] ' is true there: trailing spaces never split a group, and email <> TRIM(email) only finds leading ones. Use DATALENGTH(email) <> DATALENGTH(TRIM(email)) to find trailing spaces on SQL Server.

Variations

Quantify how much whitespace is in the column

SELECT COUNT(*) AS rows_with_padding
FROM customers
WHERE email IS NOT NULL
  AND email <> TRIM(email);

Trim inside the string too (PostgreSQL regexp)

PostgreSQL
SELECT regexp_replace(email, '\s+', '', 'g') AS squeezed, COUNT(*) AS occurrences
FROM customers
WHERE email IS NOT NULL
GROUP BY 1
HAVING COUNT(*) > 1;

Questions that come up

Does TRIM remove tabs and newlines too?

No. Plain TRIM removes spaces only, so tab- and newline-padded values survive it. Most engines let you name the characters to strip: TRIM(BOTH CHR(9) FROM email) on PostgreSQL and Oracle, TRIM(CHAR(9) FROM email) on SQL Server 2017+, TRIM(BOTH CHAR(9) FROM email) on MySQL, trim(email, char(9) || ' ') on SQLite. The regexp variant or a nested REPLACE catches them anywhere in the string.

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.