I have a unique index to prevent users from taking identical, case insensitive, names:
CREATE UNIQUE INDEX accounts_lower_idx ON public.accounts USING btree (lower((account_name)::text))
Recently it came to my attention that some pairs of users did have these kinds of identical names.
Under normal cases, attempting to insert a user with a duplicate name will fail:
SQL Error [23505]: ERROR: duplicate key value violates unique constraint "accounts_lower_idx"
Detail: Key (lower(account_name::text))=(cogg) already exists.
But these duplicate names are still popping up, somehow.
Attempting to create a duplicate index will result in an error:
SQL Error [23505]: ERROR: could not create unique index "accounts_lower_idx_1"
Detail: Key (lower(account_name::text))=(some name) is duplicated.
I'm not making any fancy changes to these rows. I'm using trivial insert statements, and names are not changed once set.
This isn't another question about duplicate NULL's being allowed. account_name
is marked not null.
Is there some reason this wouldn't work? Is using indexes for this bad practice? Should a constraint be used instead? As far as I understand, constraints use a unique index internally. In any case, the fact that trying to make a duplicate index fails seems to indicate something has gone badly wrong.
In case it's relevant, my postgres version:
postgres (PostgreSQL) 10.18 (Ubuntu 10.18-1.pgdg20.04+1)