Received: from localhost (unknown [200.46.204.191]) by postgresql.org (Postfix) with ESMTP id 544599F9977 for ; Wed, 5 Sep 2007 11:14:13 -0300 (ADT) Received: from postgresql.org ([200.46.204.71]) by localhost (mx1.hub.org [200.46.204.191]) (amavisd-maia, port 10024) with ESMTP id 76297-02 for ; Wed, 5 Sep 2007 11:14:07 -0300 (ADT) X-Greylist: from auto-whitelisted by SQLgrey-1.7.5 Received: from oxford.xeocode.com (unknown [62.232.55.118]) by postgresql.org (Postfix) with ESMTP id AC7359F97E8 for ; Wed, 5 Sep 2007 11:14:07 -0300 (ADT) Received: from localhost ([127.0.0.1] helo=oxford.xeocode.com) by oxford.xeocode.com with esmtp (Exim 4.67) (envelope-from ) id 1ISvdo-0004w3-MA; Wed, 05 Sep 2007 15:14:00 +0100 To: Cc: "JS Ubei" , Subject: Re: optimize query with a maximum(date) extraction In-Reply-To: <20070905132250.GA30304@depesz.com> (hubert depesz lubaczewski's message of "Wed\, 5 Sep 2007 15\:22\:50 +0200") User-Agent: Gnus/5.11 (Gnus v5.11) Emacs/22.1 (gnu/linux) X-Draft-From: ("nnimap+mail01.enterprisedb.com:INBOX" 35908) References: <302443.65402.qm@web26209.mail.ukl.yahoo.com> <87abs1qrhu.fsf@oxford.xeocode.com> <20070905132250.GA30304@depesz.com> From: Gregory Stark Organization: EnterpriseDB Date: Wed, 05 Sep 2007 15:14:00 +0100 Message-ID: <871wddqjx3.fsf@oxford.xeocode.com> MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii X-Virus-Scanned: Maia Mailguard 1.0.1 X-Archive-Number: 200709/45 X-Sequence-Number: 26590 "hubert depesz lubaczewski" writes: > 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. Cute. I didn't think of that, thanks -- Gregory Stark EnterpriseDB http://www.enterprisedb.com