Let me use a simple sample to describe my question. Say I have a table t that has only two fields, auto 'id', and a jsonb typed 'info' field:
CREATE TABLE t(
ID serial NOT NULL PRIMARY KEY,
info jsonb NOT NULL
);
'info' might have fields 'a', 'b', 'c' as well as some other fields. Field 'c' might be null, and I want to (a, b, c) to be unique, so I created a unique index on them:
CREATE UNIQUE INDEX idx_abc ON t (
(info ->> 'a'), (info ->> 'b'), (info ->> 'c')
);
But then I realized that, if 'c' is null, this unique constraint doesn't work at all. For example, I can insert multiple rows of:
insert into t(info) values('{"a": "a1", "b": "b1"}')
or
insert into t(info) values('{"a": "a1", "b": "b1", "c": null}')
My current solution is to anyway give "c" a value, if "c" is null, then I set "null":
insert into t(info) values('{"a": "a1", "b": "b1", "c": "null"}')
this way will trigger the unique constraint if I run the insert twice. But I feel this is just a workaround, I wonder if there is a better to solution to allow the unique constraint to work even if field "c" is null.