Received: from localhost (unknown [200.46.204.184]) by postgresql.org (Postfix) with ESMTP id 33FD89FA117 for ; Wed, 5 Sep 2007 08:30:34 -0300 (ADT) Received: from postgresql.org ([200.46.204.71]) by localhost (mx1.hub.org [200.46.204.184]) (amavisd-maia, port 10024) with ESMTP id 73262-02 for ; Wed, 5 Sep 2007 08:30:21 -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 0B24C9FA062 for ; Wed, 5 Sep 2007 08:30:27 -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 1ISt5R-000182-R4; Wed, 05 Sep 2007 12:30:21 +0100 To: "JS Ubei" Cc: Subject: Re: optimize query with a maximum(date) extraction In-Reply-To: <302443.65402.qm@web26209.mail.ukl.yahoo.com> (JS Ubei's message of "Wed\, 5 Sep 2007 09\:53\:22 +0000 \(GMT\)") User-Agent: Gnus/5.11 (Gnus v5.11) Emacs/22.1 (gnu/linux) X-Draft-From: ("nnimap+mail01.enterprisedb.com:INBOX.performance" 2262) References: <302443.65402.qm@web26209.mail.ukl.yahoo.com> From: Gregory Stark Organization: EnterpriseDB Date: Wed, 05 Sep 2007 12:30:21 +0100 Message-ID: <87abs1qrhu.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/39 X-Sequence-Number: 26584 "JS Ubei" writes: > Hi all, > > I need to improve a query like : > > SELECT id, min(the_date), max(the_date) FROM my_table GROUP BY id; > > Stupidly, I create a B-tree index on my_table(the_date), witch is logically > not used in my query, because it's not with a constant ? isn't it ? That's not so stupid, it would be possible for a database to make use of such an index for this query. But it's not one of the plans Postgres knows how to execute. I don't think you'll find anything much faster for this particular query. You could profile running these two (non-standard) queries: 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. -- Gregory Stark EnterpriseDB http://www.enterprisedb.com