Postgresql: Conditionally unique constraint

PostgreSQL doesn’t define a partial (i.e. conditional) UNIQUE constraint – however, you can create a partial unique index.

PostgreSQL uses unique indexes to implement unique constraints, so the effect is the same, with an important caveat: you can’t perform upserts (ON CONFLICT DO UPDATE) against a unique index like you would against a unique constraint.

Also, you won’t see the constraint listed in information_schema.

CREATE UNIQUE INDEX stop_myc ON stop (col_a) WHERE (col_b is NOT null);

See partial indexes.

Leave a Comment