2

if we write a trigger FOR STATEMENT like below how can we access only updated rows in trigger procedure/function

CREATE FUNCTION func1()
RETURNS trigger AS $$
BEGIN
    --access only updated/inserted rows here???
    RETURN null;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER trig1
AFTER UPDATE OR DELETE OR INSERT
ON tbl1 FOR STATEMENT
EXECUTE PROCEDURE func1();

I mean when there are multiple rows updated once like below

update tbl1 set col1=1 where col2 in (2,3,4,5,6)
3
  • I don't think you can. I think you need to use row triggers and go through NEW and OLD. Commented Mar 24, 2014 at 5:10
  • @mu is too short thanks for reply, I am using postgres 9.3, you mean it is not supported yet? there is no performance difference even if we use FOR EACH ROW for table updates of hundreds or thousands rows at once? Commented Mar 24, 2014 at 5:20
  • @RAFIQ There'd be a big performance difference if it was supported, but since PostgreSQL doesn't support NEW and OLD for FOR EACH STATEMENT triggers, FOR EACH ROW is your only option. Commented Mar 24, 2014 at 5:21

2 Answers 2

8

Now, it is possible to use an identifier for the table of inserted records in pg 10 :

CREATE TRIGGER transfer_insert
AFTER INSERT ON transfer
REFERENCING NEW TABLE AS inserted
FOR EACH STATEMENT
EXECUTE PROCEDURE check_transfer_balances_to_zero();

Extracted from pg 10 doc : https://www.postgresql.org/docs/10/static/sql-createtrigger.html

Sign up to request clarification or add additional context in comments.

Comments

2

At this time there is no support for NEW and OLD pseudo-relations for FOR EACH STATEMENT triggers.

You must use FOR EACH ROW triggers.

In theory it's possible for PostgreSQL to have fake tables for the new- and old- row versions, connected together by some one-off generated key. Or a single table containing the new and old tuples as composite types. However, this is not currently supported, and as far as I know nobody is working on support for it.

For some applications it can be worth using FOR EACH ROW triggers to INSERT into a TEMPORARY table, then process the whole lot in a final FOR EACH STATEMENT trigger.

1 Comment

Thanks very much for clarification, i really wasted lot of time looking for help, now will move on with FOR EACH ROW triggers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.