I have the following table:
mytable
---------
id Serial PK
action Integer
model VARCHAR
model_id integer
active BOOL
But due to my logic there cannot be duplicate values having the same values for model,model_id,action
when active is true.
Therefore, I place a unique constraint:
ALTER TABLE mytable ADD CONSTRAINT constraint_name UNIQUE (model,model_id,action,active);
But that does not avoid me having the unique constraint only when active=true. Also, my table is pre-populated with duplicate values therefore I want to set active=false on dduplicate ones and keep only one record with value=true
do you know any good idea on how I can do this beyond just writing an update statement before applying the constraint?
CREATE UNIQUE INDEX index_name ON mytable (model, model_id, action) WHERE (active)
SELECT * FROM mytable WHERE active = FALSE ;
?