Postgresql – Trigger function error: Record “old” not yet assigned

functionspostgresqltrigger

I'm new to trigger functions and trying to work this out. I have looked for solutions in the documentation and applied those, but still something is wrong here. My aim is to show error an message when inserting into this specific column.

CREATE OR REPLACE FUNCTION test_f() 
    RETURNS TRIGGER
    LANGUAGE plpgsql
    AS $$
    BEGIN
    IF (TG_OP = 'INSERT') THEN 
    IF (OLD.col1 != NEW.col1) THEN
        RAISE EXCEPTION 'Editing not allowed';
        END IF;
        END IF;
        RETURN NEW;
        END;
    $$;

    CREATE TRIGGER test_t
    Before insert on schema.table
    For each row execute procedure test_f();

    Insert into schema.table(col1)
    VALUES
    ('test');

(I'm aware there are questions like mine already however those haven't helped in my case.)

Best Answer

In the case of an INSERT, there is no previous version of the row, so the OLD variable is unassigned.

See the documentation:

OLD

   Data type RECORD; variable holding the old database row for UPDATE/DELETE operations in row-level triggers. This variable is null in statement-level triggers and for INSERT operations.