Received: from localhost (unknown [200.46.204.182]) by postgresql.org (Postfix) with ESMTP id 12C542E3670 for ; Fri, 30 Nov 2007 05:41:59 -0400 (AST) Received: from postgresql.org ([200.46.204.71]) by localhost (mx1.hub.org [200.46.204.182]) (amavisd-maia, port 10024) with ESMTP id 28384-05 for ; Fri, 30 Nov 2007 05:41:46 -0400 (AST) Received: from depesz.com (depesz.com [88.198.37.40]) by postgresql.org (Postfix) with ESMTP id 7972B2E2F41 for ; Fri, 30 Nov 2007 05:41:49 -0400 (AST) Received: from depesz by depesz.com with local (Exim 4.63) (envelope-from ) id 1Iy2NW-0003CU-Qu; Fri, 30 Nov 2007 10:41:46 +0100 Date: Fri, 30 Nov 2007 10:41:46 +0100 From: hubert depesz lubaczewski To: Christian Kindler Cc: Pavel Stehule , Stephen Cook , pgsql-sql@postgresql.org Subject: Re: statement-level trigger sample out there? Message-ID: <20071130094146.GA10972@depesz.com> Reply-To: depesz@depesz.com References: <20071129150454.99350@gmx.net> MIME-Version: 1.0 Content-Type: text/plain; charset=utf-8 Content-Disposition: inline In-Reply-To: <20071129150454.99350@gmx.net> User-Agent: Mutt/1.5.13 (2006-08-11) X-Virus-Scanned: Maia Mailguard 1.0.1 X-Archive-Number: 200711/161 X-Sequence-Number: 29689 On Thu, Nov 29, 2007 at 04:04:54PM +0100, Christian Kindler wrote: > I have a realy big table (> 2'000'000 records). every second there are several inserts and updates. the thing is i need a last row reference depending on a foreing_key. > > something like this: > > id, foreign_key, last_id, value1, value1, date > >1<, 3, null, 12, 13, 2007-01-01 > >2<, 4, null, 11, 10, 2007-01-01 > 4, 3, >1<, 12, 13, 2007-01-02 > 5, 4, >2<, 11, 10, 2007-01-02 > ... > > of course the sequence can have holes so I have to calculate the real last row id. for now i calculate for each row by invoking a "select max(id) where foreign_key = $1" but this cost a lot of performance. I could do this easily with one update for the whole query - if i could know which foreign_key and which date range was performed. create index q on table (foreing_key, id); and then: select max(id) from table where foreing_key = ?; should be very fast. if it is not: select id from table where foreing_key = ? order by foreing_key desc, id desc limit 1; will be fast. of course - remember about vacuum/analyze. depesz -- quicksil1er: "postgres is excellent, but like any DB it requires a highly paid DBA. here's my CV!" :) http://www.depesz.com/ - blog dla ciebie (i moje CV)