Re: Trigger on Insert to Update only newly inserted fields?

From: Michael Fuhr <mike(at)fuhr(dot)org>
To: Henry Ortega <juandelacruz(at)gmail(dot)com>
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: Trigger on Insert to Update only newly inserted fields?
Date: 2006-08-29 10:38:58
Message-ID: 20060829103857.GA20419@winnie.fuhr.org
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

On Mon, Aug 28, 2006 at 11:53:36AM -0400, Henry Ortega wrote:
> CREATE FUNCTION updated_end_date() RETURNS trigger AS '
> BEGIN
> update table set end_date=(select effective-1 from table t2 where
> t2.employee=table.employee and t2.effective>table.effective order by
> t2.effective limit 1);
> RETURN NEW;
> END;
> ' LANGUAGE 'plpgsql';
>
> That updates ALL of the records in the table which takes so long.
> Should I be doing things like this? Or is the update query on my trigger
> function so wrong?

You're updating the same table that has the trigger? Beware of
endless trigger recursion.

You're not restricting the UPDATE with a WHERE clause, which explains
why it updates the entire table. Maybe you meant this:

update table set end_date = (...) where employee = new.employee;

The subselect for each row also slows down the update, although you
might not be able to avoid that if requirements demand a potentially
distinct end_date for each row.

--
Michael Fuhr

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Jaime Casanova 2006-08-29 12:33:42 Re: dinamic sql
Previous Message Manso Gomez, Ramon 2006-08-29 10:31:22 dinamic sql