Home > database >  How to create a trigger in postgresql
How to create a trigger in postgresql

Time:01-06

I need to create a trigger in postgres where, when I add a record to table A, it automatically inserts its primary key value (which is auto incremented) into table B, the primary key of table A is the foreign key in table B.

I have tried doing it through pgadmin but it does not allow me to save. Could someone help out please.

CodePudding user response:

First create the following trigger function.

CREATE OR REPLACE FUNCTION auto_insert() RETURNS TRIGGER AS
$BODY$
BEGIN
    INSERT INTO
        B(a_id)
        VALUES(new.id);

           RETURN new;
END;
$BODY$
language plpgsql;

And then attach the trigger function to table A.

CREATE TRIGGER auto_inserter
 AFTER INSERT ON A
 FOR EACH ROW
 EXECUTE PROCEDURE auto_insert();
  • Related