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?
-
1Could you provide some more details? Is this "different table" a single, separate table, or multiple tables based on some value of some field in awards.jcater– jcater2012-09-10 02:35:16 +00:00Commented Sep 10, 2012 at 2:35
-
2postgresql.org/docs/8.1/static/triggers.htmlertx– ertx2012-09-10 06:21:10 +00:00Commented Sep 10, 2012 at 6:21
-
2@ertx Better to link to the /current/ doc instead of the /8.1/ doc, that's extremely out of date.Craig Ringer– Craig Ringer2012-09-10 07:02:26 +00:00Commented Sep 10, 2012 at 7:02
-
Didn't knew postgresql documentation had this feature, thanks, Craigertx– ertx2012-09-10 08:44:26 +00:00Commented Sep 10, 2012 at 8:44
-
2@ertx: More about referencing the PostgreSQL manual on meta.SO.Erwin Brandstetter– Erwin Brandstetter2012-09-10 21:04:39 +00:00Commented Sep 10, 2012 at 21:04
Add a comment
|
2 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();
3 Comments
Andrew Ramnikov
In the trigger Function how das it knows to insert values from table one? Don't we need to write "from table1" after "values(new.id, new.name)"?
minisaurus
new.id and new.name are the values from table1
Abel Callejo
Is the nEw stuff case-sensitive? Does
new
or NEW
do?You want the documenation for PL/PgSQL triggers, which discusses just this case among others. The general documentation on triggers may also be useful.
You can use either a BEFORE
or AFTER
trigger for this. I'd probably use an AFTER
trigger so that my trigger saw the final version of the row being inserted, though. You want FOR EACH ROW
, of course.
3 Comments
rosenthal
Hey @Craig Ringer is the purpose of FOR EACH ROW for batch inserts?
Craig Ringer
@rosenthal Huh?
FOR EACH STATEMENT
triggers don't have access to the NEW
row. So even if you were doing a single row INSERT
it wouldn't be useful for this.rosenthal
I didn't mean that, pardon my poor choice in words. I mean what is the FOR EACH ROW do? I looked at the documentation for Postgres and understand it now. "A trigger that is marked FOR EACH ROW is called once for every row that the operation modifies. "