0

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.

5
  • What error are you getting? Commented Jan 4, 2023 at 17:14
  • all you need to do is read the documentation enterprisedb.com/postgres-tutorials/… Commented Jan 4, 2023 at 17:17
  • and here stackoverflow.com/questions/16102188/… Commented Jan 4, 2023 at 17:36
  • Show us your code please Commented Jan 4, 2023 at 17:39
  • 1) It is spelled out in the docs plpgsql triggers. 2) Not sure what the purpose of this is? Without the rest of the row in table B filled in having just the FK does not really do anything. Commented Jan 4, 2023 at 17:44

1 Answer 1

0

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();
Sign up to request clarification or add additional context in comments.

1 Comment

Change "After insert on" to "Before insert on" if the trigger should be executed before inserting the data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.