I have table_1 and table_1_history in PostgreSQL. I have setup a trigger for insert, update, delete on table_1. So any changes in table_1 will reflect to table_1_history and will create a new row. This is working fine.
Begin
If (TG_OP = 'DELETE') THEN
INSERT INTO table_1_history SELECT OLD.*;
ELSEIF (TG_OP = 'UPDATE') THEN
INSERT INTO table_1_history SELECT NEW.*;
ELSEIF (TG_OP = 'INSERT') THEN
INSERT INTO table_1_history SELECT NEW.*;
END IF;
RETURN NULL;
END;
PK for table_1 = id, effective_date PK for table_1_history = id, effective_date, update_timestamp
I have a new requirement to delete records from table_1 which are older than 30 days. While doing so I am getting error the "record_1 already exists in history which violates unique constraint". To make it work I need to delete record_1 from table_1_history or change update timestamp of table_1_history.
Is there any other way to handle this scenario?
update_timestampis set) then theDELETEwill have the sameupdate_timestampas existing record in the history table. You need to add a field in the history table that makes each row unique, quick option would be auto increment field usingGENERATE IDENTITY.