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();