I need to create a restriction on a table based on four columns, and two of them are mutually exclusive, I mean, if one is NULL the other is not.
The ideal script would be this:
ALTER TABLE ONLY t_users_prizes
ADD CONSTRAINT t_user_prize_test_circuit_key
UNIQUE (id_event||':'||id_circuit, id_prize, id_user);
But Postgres doesn’t allow this kind of concatenation.
How can I implement this restriction?
NULLvalues do not violate aUNIQUEconstraint – twoNULLare not considered equal! So a simpleUNIQUEconstraint doesn’t work.You can get it done with two partial
UNIQUEindexes and aCHECKconstraint:I declared
canddasNOT NULL, to prevent further complications.See:
To also disallow
(1, NULL, 3, 4)and(NULL, 1, 3, 4), you could use one index withCOALESCEinstead: