Finding duplicate emails
Duplicate emails are found by grouping on LOWER(TRIM(email)) with HAVING COUNT(*) > 1, and the records themselves come from a window COUNT or EXISTS. A duplicate usually means uniqueness is not enforced in the database: an existence check separate from the insert lets two simultaneous requests through, so the race is proved with two parallel registrations. The guarantee is a unique index on the normalised expression, created after cleanup.
SQL · Tasks
One address, yet two accounts. How to find out why it happened and prevent it from happening again?
In the task "find the emails that repeat" the query showed that anna is in three records and oleh in two. That is a symptom. A duplicate email in a system is rarely an accident: it is a consequence of a rule the backend did not enforce in the database. The "does this address exist?" check runs apart from the insert, case and whitespace are not normalised, and two simultaneous requests pass the check together. QA has three tasks here: show the records themselves, prove the cause and make sure the database lacks a constraint. The sample is the same: ids 1, 2, 3 are anna in three variants, ids 4 and 5 are oleh, ids 7 and 8 have email NULL.
Which exact records. Grouping gives the value and a counter, but not the ids. To open each record and compare them you need the rows.
-- which exact records (ids 1, 2, 3, 4, 5)
SELECT u.*
FROM users u
WHERE EXISTS (
SELECT 1 FROM users d
WHERE d.id <> u.id
AND LOWER(TRIM(d.email)) = LOWER(TRIM(u.email))
);
The query compares each record with all the others by equality, and NULL = NULL is not true, so NULL rows stay out by themselves (grouping, by contrast, would collect them into one group). The drawback of EXISTS: it joins the table to itself, so on a big table it is heavier than grouping. PostgreSQL usually runs it as a hash join on the expression, and an index on LOWER(TRIM(email)) may let it look the match up by index, depending on the plan.
How to prevent it from happening again. A check in the application without a database constraint is unreliable. If the code first runs a SELECT "does this address exist?" and then an INSERT, two simultaneous requests both see "no" and both insert. The only guarantee is a unique index over the normalised expression. It is created after cleanup, because with duplicates present it cannot be created.
CREATE UNIQUE INDEX users_email_norm_key
ON users (LOWER(TRIM(email)));
A repeated insert with the same address now gives a uniqueness error, which the backend must turn into a 409 response. The index allows several rows with NULL. If an empty email is forbidden, the column is made NOT NULL, and PostgreSQL 15 and newer also have UNIQUE NULLS NOT DISTINCT. Case-insensitivity can also be provided by the citext type from an extension.
How to test the race. The test sends two identical registration requests at the same moment and looks at the response codes and the number of records in the database.
const body = JSON.stringify({ email: 'race@test.com', password: 'Passw0rd!' });
const send = () =>
fetch(`${base}/users`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body,
});
const res = await Promise.all([send(), send()]);
console.log(res.map((r) => r.status));
// expect one 201 and one 409 in any order; two 201s mean there is no constraint
After the test the database is checked with SELECT COUNT(*) FROM users WHERE email = 'race@test.com': it must be 1. If the same request sent after the first one gets 409 while two simultaneous ones give [201, 201] and two rows, the duplicate is created by a race, not by missing validation.
Common mistakes.
- Looking for duplicates by the raw email: variants with case and whitespace stay unnoticed.
- Believing the backend check is enough without a unique index in the database.
- Creating the index without removing duplicates first: the operation fails.
- Not checking NULL: false duplicates in the report or, conversely, missed empty values.
Check yourself
Why does the EXISTS query not show records with email NULL, while the GROUP BY query without IS NOT NULL shows them as a duplicate?
Answer
GROUP BY treats all NULLs as one value and collects them into one group. EXISTS compares with =, and NULL = NULL gives UNKNOWN, so there is no match. These are two different semantics, so the results of the two queries must be interpreted differently.
After CREATE UNIQUE INDEX … ON users (LOWER(TRIM(email))) the race test still gives [201, 201]. What should be checked?
Answer
Whether the index really exists and is valid in the very database the test uses, and how many rows the database really has: if one, the backend swallows the uniqueness error and answers 201 instead of 409. Also whether the application inserts into another table or schema. The query SELECT indexdef FROM pg_indexes WHERE tablename = 'users' shows what exists.