Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert trigger to Update another table using PostgreSQL

I have a table named awards. How can I mount a Trigger in PostgreSQL where each insert in the table awards updates a different table?

like image 709
user1658873 Avatar asked Sep 10 '12 00:09

user1658873


People also ask

How do I use triggers in PostgreSQL?

Syntax. CREATE TRIGGER trigger_name [BEFORE|AFTER|INSTEAD OF] event_name ON table_name [ -- Trigger logic goes here.... ]; Here, event_name could be INSERT, DELETE, UPDATE, and TRUNCATE database operation on the mentioned table table_name. You can optionally specify FOR EACH ROW after table name.

Is it possible to create the following trigger before or after update trigger for each row?

Old and new values are available in both BEFORE and AFTER row triggers. A new column value can be assigned in a BEFORE row trigger, but not in an AFTER row trigger (because the triggering statement takes effect before an AFTER row trigger is fired).

How do I know if my trigger is insert or update?

Triggers have special INSERTED and DELETED tables to track "before" and "after" data. So you can use something like IF EXISTS (SELECT * FROM DELETED) to detect an update. You only have rows in DELETED on update, but there are always rows in INSERTED . Look for "inserted" in CREATE TRIGGER.


1 Answers

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(); 
like image 194
Sachin Gupta Avatar answered Sep 28 '22 03:09

Sachin Gupta