46

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?

5
  • 1
    Could 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. Commented Sep 10, 2012 at 2:35
  • 2
    postgresql.org/docs/8.1/static/triggers.html Commented 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. Commented Sep 10, 2012 at 7:02
  • Didn't knew postgresql documentation had this feature, thanks, Craig Commented Sep 10, 2012 at 8:44
  • 2
    @ertx: More about referencing the PostgreSQL manual on meta.SO. Commented Sep 10, 2012 at 21:04

2 Answers 2

91

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 to request clarification or add additional context in comments.

3 Comments

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)"?
new.id and new.name are the values from table1
Is the nEw stuff case-sensitive? Does new or NEW do?
6

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

Hey @Craig Ringer is the purpose of FOR EACH ROW for batch inserts?
@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.
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. "

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.