Skip to content

Instantly share code, notes, and snippets.

@somerongit
Created July 21, 2022 03:44
Show Gist options
  • Save somerongit/869d68f7ff3df5938e95464acdfef8f8 to your computer and use it in GitHub Desktop.
Save somerongit/869d68f7ff3df5938e95464acdfef8f8 to your computer and use it in GitHub Desktop.
Insert trigger to Update another table using PostgreSQL
https://stackoverflow.com/questions/12343984/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();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment