X-Original-To: pgsql-sql-postgresql.org@postgresql.org Received: from localhost (mx1.hub.org [200.46.208.251]) by postgresql.org (Postfix) with ESMTP id 544509FAE4E for ; Tue, 29 Aug 2006 07:39:13 -0300 (ADT) Received: from postgresql.org ([200.46.204.71]) by localhost (mx1.hub.org [200.46.208.251]) (amavisd-new, port 10024) with ESMTP id 54421-07 for ; Tue, 29 Aug 2006 07:39:08 -0300 (ADT) X-Greylist: from auto-whitelisted by SQLgrey- Received: from tigger.fuhr.org (tigger.fuhr.org [63.214.45.158]) by postgresql.org (Postfix) with ESMTP id 4BD839FA4D0 for ; Tue, 29 Aug 2006 07:39:08 -0300 (ADT) Received: from winnie.fuhr.org (winnie.fuhr.org [10.1.0.1]) by tigger.fuhr.org (8.13.8/8.13.8) with ESMTP id k7TAcxiU042241 (version=TLSv1/SSLv3 cipher=DHE-RSA-AES256-SHA bits=256 verify=OK); Tue, 29 Aug 2006 04:39:01 -0600 (MDT) Received: from winnie.fuhr.org (localhost [127.0.0.1]) by winnie.fuhr.org (8.13.8/8.13.8) with ESMTP id k7TAcwjU020568; Tue, 29 Aug 2006 04:38:58 -0600 (MDT) (envelope-from mfuhr@winnie.fuhr.org) Received: (from mfuhr@localhost) by winnie.fuhr.org (8.13.8/8.13.8/Submit) id k7TAcwSd020567; Tue, 29 Aug 2006 04:38:58 -0600 (MDT) (envelope-from mfuhr) Date: Tue, 29 Aug 2006 04:38:58 -0600 From: Michael Fuhr To: Henry Ortega Cc: pgsql-sql@postgresql.org Subject: Re: Trigger on Insert to Update only newly inserted fields? Message-ID: <20060829103857.GA20419@winnie.fuhr.org> References: <2bffcc330608280702y16c25090i816589e20163e7e8@mail.gmail.com> <20060828145737.GA5004@winnie.fuhr.org> <2bffcc330608280853x50b1034nca246a5dcc935e7@mail.gmail.com> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline In-Reply-To: <2bffcc330608280853x50b1034nca246a5dcc935e7@mail.gmail.com> X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=0.182 tagged_above=0 required=5 tests=AWL, SPF_PASS X-Spam-Level: X-Archive-Number: 200608/227 X-Sequence-Number: 26185 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