Insert trigger to Update another table using PostgreSQL

Here we have two tables named table1 and table2. Using a trigger I’ll update table2 on insertion into table1.

Create the tables

CREATE TABLE table1
(
  id integer NOT NULL,
  name character varying,
  CONSTRAINT table1_pkey PRIMARY KEY (id)
)

CREATE TABLE table2
(
  id integer NOT NULL,
  name character varying
)

The Trigger Function

CREATE OR REPLACE FUNCTION function_copy() RETURNS TRIGGER AS
$BODY$
BEGIN
    INSERT INTO
        table2(id,name)
        VALUES(new.id,new.name);

           RETURN new;
END;
$BODY$
language plpgsql;

The Trigger

CREATE TRIGGER trig_copy
     AFTER INSERT ON table1
     FOR EACH ROW
     EXECUTE PROCEDURE function_copy();

Leave a Comment