Trim whitespace then remove duplicates
Normalize whitespace with an UPDATE, then re-run the duplicate cleanup on the trimmed values, previewing and wrapping both steps in a transaction.
The task
Whitespace-padded emails hide duplicates. The fix is two moves: strip the padding, then collapse the duplicates it reveals, previewing each step before it runs.
The snippet
Runs unchanged on current versions of SQL Server, PostgreSQL, MySQL, SQLite and Oracle.
-- Step 1: how many rows have padding?
SELECT id, email FROM customers
WHERE email <> TRIM(email);
-- Open a transaction here: BEGIN / START TRANSACTION /
-- BEGIN TRANSACTION depending on the engine (implicit on Oracle)
-- Step 2: strip the padding
UPDATE customers
SET email = TRIM(email)
WHERE email <> TRIM(email);
-- Step 3: delete duplicates the trim revealed, keep lowest id
DELETE FROM customers
WHERE id IN (
SELECT id
FROM (
SELECT id,
ROW_NUMBER() OVER (PARTITION BY email ORDER BY id) AS rn
FROM customers
WHERE email IS NOT NULL
) ranked
WHERE rn > 1
);
-- check both row counts, then COMMIT or ROLLBACK
仕組み
Step 1 is the read-only preview; never skip it. Step 2 normalizes in place, only touching rows that actually change. Step 3 re-ranks by the now-clean email and deletes every copy except the first; the derived table keeps it legal on MySQL and Oracle (see delete-duplicates-keep-one). One transaction spans both writes so a bad surprise rolls back everything at once. On SQL Server, step 1 and step 2 only see leading spaces, because its comparisons ignore trailing ones; that is harmless, since trailing spaces never made two emails differ there in the first place.
Variations
Normalize several columns at once
UPDATE customers
SET email = TRIM(email),
name = TRIM(name),
phone = TRIM(phone)
WHERE email <> TRIM(email)
OR name <> TRIM(name)
OR phone <> TRIM(phone);
Questions that come up
Why not trim and dedupe in one statement?
SQL has no single statement that both rewrites a value and deletes the rows that now collide with it. Running two statements also gives you a checkpoint: the UPDATE's row count should match the step 1 preview before you let the DELETE run. If a unique index already exists on email, the UPDATE itself fails on the first collision, so on such tables delete the padded copies first and trim the survivors afterwards.
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.