I have a line_items table with following columns:
product_id
variant_id
variant_id is nullable.
Here is the condition:
- If
variant_idis NULL thenproduct_idshould be unique. - If
variant_idhas a value then combination ofproduct_idandvariant_idshould be unique.
Is that possible in PostgreSQL?
Create a
UNIQUEmulticolumn index on(product_id, variant_id):However, this allows multiple entries of
(1, null)for(product_id, variant_id)by default, becausenullvalues are not considered to be distinct values.To make up for that, additionally create a partial
UNIQUEindex onproduct_id:This way you can enter
(1,2),(1,3)and(1, null), but neither of them a second time. Also speeds up queries with conditions on one or both column.Or use the
NULLS NOT DISTINCTclause in Postgres 15 or later. See: