'Trigger, which logs/deletes a row into a separate table, before an entry with the same attribute value is inserted

I have two tables which both have the same columns and a foreign key named id. Table t1 is supposed to store the current data while table t2 is a log table.

The rows in table t1 are supposed to be unique, so I want to create a trigger which copies the data from t1 to t2 and then removes the entries in t1 (if I insert data with an id which is already found in t1).

If the id is not found in t1, the trigger is simply supposed to insert the data into t1 and do nothing with t2. I am using PostgreSQL and this is my current attempt but it doesn't seem to work:

CREATE OR REPLACE FUNCTION move_data_to_historical_measured_data_insert()
    RETURNS TRIGGER
    LANGUAGE PLPGSQL
    AS
$$
BEGIN
    IF OLD.id = NEW.id THEN  
        INSERT INTO t2(id, value, timestamp)
        VALUES(OLD.id, OLD.value, OLD.timestamp);
        DELETE FROM t1;
        RETURN NULL;
    ELSE
        RETURN NULL;
    END IF; 
END;
$$ 
    
CREATE OR REPLACE TRIGGER store_data_to_history_insert
    BEFORE INSERT 
    ON t1
    FOR EACH ROW
    EXECUTE PROCEDURE move_data_to_historical_measured_data_insert();
    


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source