Postgresql Trigger Syntax Insert or Update or Delete

2.5k views Asked by At

I am a newbie and I want to understand: I understand that New is only executed with Insert or Update. The OLD ones only with Delete "If I'm not mistaken".

And what I'm trying to do is derive "If 2 values ​​are the same but different numbers" which I insert into a table and leave the default false value, I did, but "I insert" the new data, but it should be the value "OLD" of "driver".

¿Could that request be fulfilled?

db<>fiddle

The trigger:

CREATE FUNCTION TR_DRIVER() RETURNS TRIGGER
AS
$$
BEGIN

IF EXISTS(SELECT number_driver, cod_driver
        FROM driver AS con
   WHERE  EXISTS (SELECT * FROM driver_tmp AS tmp
        WHERE con.number_driver<>tmp.number_driver AND con.cod_driver=tmp.cod_driver)) THEN

INSERT INTO driver_false(number_driver, cod_driver, full_name)
    VALUES (new.number_driver, new.cod_driver, new.full_name);
ELSE

INSERT INTO driver(number_driver, cod_driver, full_name, active)
    VALUES (new.number_driver, new.cod_driver, new.full_name, new.active)
ON CONFLICT (number_driver)
DO UPDATE SET
cod_driver=excluded.cod_driver,
full_name=excluded.full_name,
active=excluded.active;

END IF;
RETURN NEW;
END $$
LANGUAGE plpgsql;

CREATE TRIGGER TR_DRIVER_TMP AFTER INSERT OR UPDATE ON driver_tmp
FOR EACH ROW
EXECUTE PROCEDURE TR_DRIVER() ;
1

There are 1 answers

1
Adrian Klaver On

You are mistaken, OLD also exists for UPDATE as update in Postgres is actually INSERT/DELETE. For the details see:

https://www.postgresql.org/docs/current/plpgsql-trigger.html

NEW

Data type RECORD; variable holding the new database row for INSERT/UPDATE operations in row-level triggers. This variable is null in statement-level triggers and for DELETE operations. 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.