I have a line_items
table with following columns:
product_id
variant_id
variant_id
is nullable.
Here is the condition:
- If
variant_id
is NULL thenproduct_id
should be unique. - If
variant_id
has a value then combination ofproduct_id
andvariant_id
should be unique.
Is that possible in PostgreSQL?
Create a
UNIQUE
multicolumn index on(product_id, variant_id)
:However, this would allow multiple entries of
(1, NULL)
for(product_id, variant_id)
becauseNULL
values are not considered identical.To make up for that, additionally create a partial
UNIQUE
index 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.Recent, related answer on dba.SE, almost directly applicable to your case:
Another option is to use expressions in your key fields. This may not have been around when you asked the question, but could be helpful for others that come across this now.
Granted, this assumes that your
variant_id
is an auto-incrementing integer that started at 1. Also note the parentheses around the expression. Per the docs, they are required.http://www.postgresql.org/docs/9.3/static/sql-createindex.html