Rows Blocking a Unique Index
A migration is about to run
CREATE UNIQUE INDEX ON account (email) and it fails. Find the rows
that stop it.
Return one row per blocking value:
email— the duplicated value, exactly as storedcopies— how many rows hold itkeep_id— the lowestidamong them, the row the cleanup will keep
Order by email.
Two things the index does not consider duplicates.
NULL values — a unique index permits any number of them — and
values differing in case, because comparison is case-sensitive. Report neither.
Expected output
email | copies | keep_id
---------+--------+--------
a@x.test | 3 | 1
b@x.test | 2 | 4
Editorial
SELECT email, count(*) AS copies, min(id) AS keep_id
FROM account
WHERE email IS NOT NULL
GROUP BY email
HAVING count(*) > 1
ORDER BY email;
HAVING, not WHERE
WHERE count(*) > 1 is a syntax error, and the reason is the
order the clauses run in. WHERE filters rows before
grouping, when no group exists and count(*) has nothing to count.
HAVING filters groups after. Both appear here and they do
different jobs: WHERE drops the NULL rows from consideration,
HAVING drops the values that turned out not to be duplicated.
Why the NULLs are excluded
A unique index in PostgreSQL treats NULLs as distinct from each other, so
Dan and Dora both having no email blocks nothing. Without the
WHERE, GROUP BY email collects them into one group of
2 and the query reports NULL as a duplicate — a row the migration will not
object to, sent to a cleanup that would then delete a real account.
Worth knowing that this is a choice the standard leaves open and Postgres 15 made configurable:
CREATE UNIQUE INDEX ON account (email) NULLS NOT DISTINCT;
With that, two NULLs do collide and the WHERE clause
above becomes wrong. Which is the real lesson: "find the duplicates" has no
answer until you know what the index is going to consider equal.
Why the case difference is excluded
C@x.test and c@x.test are different strings, and a
B-tree on text orders them by the collation's byte comparison, so
the index accepts both. That is almost certainly not what the product wants —
two accounts, one mailbox — but it is what the migration will do, and the
statement asks what blocks the migration.
If the intent is one account per mailbox, the index has to say so:
CREATE UNIQUE INDEX account_email_lower ON account (lower(email));
and then the blocking query has to match it, grouping on the same expression:
SELECT lower(email) AS email, count(*) AS copies, min(id) AS keep_id
FROM account
WHERE email IS NOT NULL
GROUP BY lower(email)
HAVING count(*) > 1;
which now reports c@x.test as well. The duplicate query
must group on exactly the expression the index indexes. Group on
email and build the index on lower(email) and the
migration still fails after the cleanup you were told was complete.
Listing the rows instead of the groups
The groups tell you what is broken; a cleanup needs the individual rows to delete. One query for both:
SELECT id, name, email,
row_number() OVER (PARTITION BY email ORDER BY id) AS n
FROM account
WHERE email IS NOT NULL;
Every row with n > 1 is a loser, every row with
n = 1 is the keeper, and min(id) above is the same
choice expressed as an aggregate. Keeping the lowest id means keeping the
earliest account, which is a policy, not a fact — keeping the one with the most
recent login is just as defensible and is usually what the business wants. Say
which you chose.
Doing it without a write lock
Once the data is clean, the plain form holds an exclusive lock on the whole table for the duration of the build, which on a large table means an outage:
CREATE UNIQUE INDEX CONCURRENTLY account_email ON account (email);
Slower, two table passes, cannot run inside a transaction block, and it
leaves an INVALID index behind if it fails — which you then drop
and retry. On anything in production it is the only version worth using.
What an interviewer is checking
Mostly HAVING versus WHERE, which is the fastest
thing to check about someone's SQL. The strong answer goes further and asks what
"duplicate" means before writing the query, because NULL handling and case
sensitivity are where this task actually goes wrong.
account
10 rows
| idinteger | nametext | emailtext |
|---|---|---|
| 1 | Alice | a@x.test |
| 2 | Aaron | a@x.test |
| 3 | Abigail | a@x.test |
| 4 | Bob | b@x.test |
| 5 | Bella | b@x.test |
Showing 5 of 10 rows.