The first way to guarantee unique of many fields in to use constraint
create table t
(
id bigserial primary key,
val1 integer,
val2 integer,
unique (val1, val2)
);
On the other hand, we can use unique index
create table t
(
id bigserial primary key,
val1 integer,
val2 integer
);
create unique index unique_val1_val2
on t (val1, val2);
is there any difference here? mb they will work differently with null values?
I have not noticed any difference while testing
2
Answers
From the manual:
The handling of NULLs depends on you, NULLS NOT DISTINCT or NULLS DISTINCT.
The difference is none*. They enforce uniqueness exactly the same way and they offer almost the exact same level of control over the index: you’re right that one of the differences is related to null handling. Demo:
The parts that are commented out above cannot be defined within
constraint
syntax but they are allowed by the equivalentindex
syntax, and vice versa: indexes don’t acceptdeferrability
behaviour spec.There’s also a third option to enforce uniqueness, an exclusion constraint:
And this time around, while it does also use an index under the hood, it does not work the same:
It’s also harder to set up for multiple fields because you need to somehow merge them into one (array, json, range etc.).