I am trying to add a unique constraint to an existing table in Postgres on a null column named personnel_id
. Most of the records have null personnel_id
. Here’s how I do it:
ALTER TABLE "myschema"."mytable" ADD UNIQUE NULLS not distinct ("personnel_id");
And I get this error:
ERROR: could not create unique index "mytable_personnel_id_key" DETAIL: Key (personnel_id)=() is duplicated.
My Postgres version is:
psql (PostgreSQL) 15.3 (Debian 15.3-1.pgdg120+1)
2
Answers
If you specify
NULLS NOT DISTINCT
, PostgreSQL treats two NULL values as not distinct, so you will get an error.If you want NULLs to be distinct, that is, if you want several NULL values to be present in the unique column, use
NULLS DISTINCT
:The error message actually reports a conflict for empty strings, i.e. two or more instances of
''
– not the same asnull
! For conflicting null values you would see:But you get:
fiddle
You need version Postgres 15 or newer to use the
NULLS [NOT] DISTINCT
feature. See:Also:
psql is not PostgreSQL. It’s the default interactive terminal and is not necessarily in line with the Postgres version. Check your Postgres version with
SELECT version();
while being connected.Modern versions of psql also show the Postgres version on connection if it disagrees.
Example:
When starting psql 16.1 connecting to a Postgres 16.1 DB:
When connecting to a DB cluster with different Postgres version:
The second part of the display is relevant.