I have a table with these fields:
id, field_a, field_b, status I have a unique constraint on (field_a, field_b, status)
I'm using the status (mapped as Integer) to manage also a soft delete so, when I need to mark an item as DELETD, I will update the status on the corresponding value.
In this way I will be able to create a new row with the same values for field_a, field_b values but with a different status. But in this logic there is a problem: I will have a constraint unique violation if I will deleted an item that was already deleted.
For example:
Is it possible to have the same constraint but, regarding the status, I would like to use only a specific value (in this case only OK)?
When any component of unique index expression for a row is equal to NULL then this row is treated as unique anycase (because one NULL is not equal to another NULL). So:
Variant 1. Use NULL for status
column value as a mark that the row is deleted.
Variant 2. Use an expression which converts DELETED status to NULL in the index expression (if your server version allows index by an expression):
CREATE UNIQUE INDEX idx
ON tablename (field_a, field_b, (CASE WHEN status = 'DELETED' THEN NULL ELSE status END))
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.