Is it possible to enforce unique value coupled with a unique column in postgres? I am using v. 11. It would be something like this:
status = 0 | store = 5
unique(store, status = 0)
That way, I can have any value for store, but for each value, it can only have one record that's status is 0, and the rest can be any value? I am sure this question has been asked before but it seems to be specific to certain frameworks like django:
how to enforce a conditional uniqueness constraint
Or I just cannot find the right answer.
I am using loopback4 and there does not seem to be a way to specify it in the framework so I want to specify it in the database. Update: To be more explanative: I have a user who can only have ONE shopping cart with a store, not more than one. Each cart has a user_id, store_id, and status. When status is 0, the cart is in progress, when status is 1, the cart is ordered, and when status is 2, it is delivered by store. So I have a table:
id | user_id | store_id | status
...| 1 | 1 | 0
...| 1 | 1 | 1
...| 1 | 1 | 1
Above, is fine and should be allowed, but :
id | user_id | store_id | status
...| 1 | 1 | 0
...| 1 | 1 | 0 <--- Not allowed
...| 1 | 1 | 1
This is not allowed, because one use has more than one shopping cart for a store. So status = 0 and store_id should be unique.
You can create a partial unique index:
create unique index on the_table (store)
where status = 0;