Received: from localhost (unknown [200.46.204.187]) by postgresql.org (Postfix) with ESMTP id 81A8E9FA0F1 for ; Wed, 5 Sep 2007 09:06:10 -0300 (ADT) Received: from postgresql.org ([200.46.204.71]) by localhost (mx1.hub.org [200.46.204.187]) (amavisd-maia, port 10024) with ESMTP id 12859-06 for ; Wed, 5 Sep 2007 09:06:00 -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 B341D9FA0BE for ; Wed, 5 Sep 2007 09:06:05 -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 1IStdx-00018m-C4; Wed, 05 Sep 2007 13:06:01 +0100 To: "JS Ubei" Cc: Subject: Re: optimize query with a maximum(date) extraction In-Reply-To: <87abs1qrhu.fsf@oxford.xeocode.com> (Gregory Stark's message of "Wed\, 05 Sep 2007 12\:30\:21 +0100") User-Agent: Gnus/5.11 (Gnus v5.11) Emacs/22.1 (gnu/linux) X-Draft-From: ("nnimap+mail01.enterprisedb.com:INBOX.performance" 2264) References: <302443.65402.qm@web26209.mail.ukl.yahoo.com> <87abs1qrhu.fsf@oxford.xeocode.com> From: Gregory Stark Organization: EnterpriseDB Date: Wed, 05 Sep 2007 13:06:01 +0100 Message-ID: <87642pqpue.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/40 X-Sequence-Number: 26585 "Gregory Stark" writes: > "JS Ubei" writes: > >> I need to improve a query like : >> >> SELECT id, min(the_date), max(the_date) FROM my_table GROUP BY id; >... > 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 Something else you might try: select id, (select min(the_date) from my_table where id=x.id) as min_date, (select max(the_date) from my_table where id=x.id) as max_date from (select distinct id from my_table) Recent versions of Postgres do know how to use the index for a simple ungrouped min() or max() like these subqueries. This would be even better if you have a better source for the list of distinct ids you're interested in than my_table. If you have a source that just has one record for each id then you won't need an extra step to eliminate duplicates. -- Gregory Stark EnterpriseDB http://www.enterprisedb.com