Received: from localhost (unknown [200.46.204.183]) by postgresql.org (Postfix) with ESMTP id 58A619FA03A for ; Wed, 5 Sep 2007 10:23:00 -0300 (ADT) Received: from postgresql.org ([200.46.204.71]) by localhost (mx1.hub.org [200.46.204.183]) (amavisd-maia, port 10024) with ESMTP id 26392-09 for ; Wed, 5 Sep 2007 10:22:56 -0300 (ADT) X-Greylist: from auto-whitelisted by SQLgrey-1.7.5 Received: from depesz.com (depesz.com [88.198.37.40]) by postgresql.org (Postfix) with ESMTP id 20B699F9BDA for ; Wed, 5 Sep 2007 10:22:56 -0300 (ADT) Received: from depesz by depesz.com with local (Exim 4.63) (envelope-from ) id 1ISuqI-0007uB-Az; Wed, 05 Sep 2007 15:22:50 +0200 Date: Wed, 5 Sep 2007 15:22:50 +0200 From: hubert depesz lubaczewski To: Gregory Stark Cc: JS Ubei , pgsql-performance@postgresql.org Subject: Re: optimize query with a maximum(date) extraction Message-ID: <20070905132250.GA30304@depesz.com> Reply-To: depesz@depesz.com References: <302443.65402.qm@web26209.mail.ukl.yahoo.com> <87abs1qrhu.fsf@oxford.xeocode.com> MIME-Version: 1.0 Content-Type: text/plain; charset=utf-8 Content-Disposition: inline In-Reply-To: <87abs1qrhu.fsf@oxford.xeocode.com> User-Agent: Mutt/1.5.13 (2006-08-11) X-Virus-Scanned: Maia Mailguard 1.0.1 X-Archive-Number: 200709/44 X-Sequence-Number: 26589 On Wed, Sep 05, 2007 at 12:30:21PM +0100, Gregory Stark wrote: > SELECT DISTINCT ON (id) id, the_date AS min_date FROM my_table ORDER BY id, the_date ASC > SELECT DISTINCT ON (id) id, the_date AS max_date FROM my_table ORDER BY id, the_date DESC > I think the first of these can actually use your index but the latter can't > unless you create one for it specifically (which is not so easy -- it'll be > easier in 8.3 though). Worse, I'm not really sure it'll be any faster than the > query you already have. it's easy to fix the second query (fix to use index) - just change order by to: order by id desc, the_date desc. 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)