RE: unique index with several columns

From: Klaus Kaisersberger <woodconsult(at)outlook(dot)de>
To: "pgsql-sql(at)lists(dot)postgresql(dot)org" <pgsql-sql(at)lists(dot)postgresql(dot)org>
Subject: RE: unique index with several columns
Date: 2022-03-04 20:02:07
Message-ID: PAXP193MB2058AB2DF5D9A24C32C726E9E3059@PAXP193MB2058.EURP193.PROD.OUTLOOK.COM
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

Here a usable example for an arbitrary number of columns (might require casting the columns to e.g. bit varying before making the arrays):
Just replace c1,c2 with your (casted) number of columns on index creation.

create function fn(cs anyelement)
returns int
as
'select count(1) from unnest(cs) t(c) where c is not null;'
language sql
immutable;

create unique index idx on t ((
case
when fn(ARRAY[c1,c2])=0 then null
else ARRAY[c1,c2]
end
));

Result:

db=# insert into t(c1,c2) values (null,null);
INSERT 0 1
db=# insert into t(c1,c2) values (null,null);
INSERT 0 1
db=# insert into t(c1,c2) values (null,null);
INSERT 0 1
db=# insert into t(c1,c2) values (1,null);
INSERT 0 1

db=# insert into t(c1,c2) values (1,null);
ERROR: duplicate key value violates unique constraint "idx"
DETAIL: Key ((
CASE
WHEN fn(ARRAY[c1, c2]) = 0 THEN NULL::integer[]
ELSE ARRAY[c1, c2]
END))=({1,NULL}) already exists.

db=# insert into t(c1,c2) values (null,1);
INSERT 0 1

db=# insert into t(c1,c2) values (null,1);
ERROR: duplicate key value violates unique constraint "idx"
DETAIL: Key ((
CASE
WHEN fn(ARRAY[c1, c2]) = 0 THEN NULL::integer[]
ELSE ARRAY[c1, c2]
END))=({NULL,1}) already exists.
db=# insert into t(c1,c2) values (null,2);
INSERT 0 1

db=# insert into t(c1,c2) values (null,2);
ERROR: duplicate key value violates unique constraint "idx"
DETAIL: Key ((
CASE
WHEN fn(ARRAY[c1, c2]) = 0 THEN NULL::integer[]
ELSE ARRAY[c1, c2]
END))=({NULL,2}) already exists.

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Alexey M Boltenkov 2022-03-04 20:47:12 Re: unique index with several columns
Previous Message Klaus Kaisersberger 2022-03-04 19:18:07 RE: unique index with several columns