Have a table named People
, column address_id (int)
and is_deleted (boolean)
, how can I add a unique constraint to allow unique address_id
+ false
, and allow multiple address_id
+ true
.
eg
address_id | is_deleted
-----------------------
1 | false
2 | true
2 | true
2 | true
thanks!
how can I add a unique constraint to allow unique address_id + false, and allow multiple address_id + true
Can't use a CHECK as that would not work in case of concurrent insertion or updates.
You can use a conditional unique index:
CREATE UNIQUE INDEX people_addr_id_is_deleted_unique
ON People (address_id) WHERE (NOT is_deleted);
This unique index will only contain rows satisfying the specified WHERE condition. Depending on the percentage of matching rows, this may save a bit of storage space, or a lot relative to a full index. Also, updates on a row that is not included in a conditional index do not have to spend time updating the index.
Further reading . Also google "postgresql conditional unique constraint".
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.