Received: from maia.hub.org (maia-5.hub.org [200.46.204.29]) by mail.postgresql.org (Postfix) with ESMTP id 50B55133655C for ; Mon, 24 Jan 2011 15:27:48 -0400 (AST) Received: from mail.postgresql.org ([200.46.204.86]) by maia.hub.org (mx1.hub.org [200.46.204.29]) (amavisd-maia, port 10024) with ESMTP id 97973-04 for ; Mon, 24 Jan 2011 19:27:41 +0000 (UTC) X-Greylist: from auto-whitelisted by SQLgrey-1.7.6 Received: from smtp.peak6.com (unknown [38.98.137.6]) by mail.postgresql.org (Postfix) with ESMTP id 75077133616B for ; Mon, 24 Jan 2011 15:27:40 -0400 (AST) X-AuditID: 0a64cb1e-b7c55ae000000bfb-3e-4d3dd2ab47f9 Message-ID: <4D3DD2AA.3070500@peak6.com> Date: Mon, 24 Jan 2011 13:27:38 -0600 From: Shaun Thomas Reply-To: sthomas@peak6.com Organization: Peak6 User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.7) Gecko/20100720 Lightning/1.0b2 Thunderbird/3.1.1 MIME-Version: 1.0 To: Dimi Paun CC: "pgsql-performance@postgresql.org" Subject: Re: How to use indexes for GROUP BY References: <1295893741.9380.984.camel@dimi.lattica.com> In-Reply-To: <1295893741.9380.984.camel@dimi.lattica.com> Content-Type: text/plain; charset="UTF-8"; format=flowed content-transfer-encoding: 7bit X-Brightmail-Tracker: AAAAAQAAAZE= X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=-1.107 tagged_above=-10 required=5 tests=BAYES_00=-1.9, RDNS_NONE=0.793 X-Spam-Level: X-Archive-Number: 201101/221 X-Sequence-Number: 42008 On 01/24/2011 12:29 PM, Dimi Paun wrote: > I want to simply get the latest "creationTS" for each location, > but that seems to result in a full table scan: > > tts_server_db=# explain analyze select location, max(creationTS) from > tagrecord group by location; Try this, it *might* work: select DISTINCT ON (location) location, creationTS from tagrecord order by location, creationTS DESC; Secondly... Postgresql 8.1? Really? If at all possible, upgrade. There is a lot you're missing from the last six years of PostgreSQL releases. For instance, your MAX means a reverse index scan for each location, which is far more expensive than an ordered index scan, so the planner may be ignoring it, if the planner in 8.1 is even that intelligent. If you were running 8.3, for instance, your index could be: create index idx_tagdata_loc_creationTS on tagRecord(location, creationTS DESC); And then suddenly it just has to use the first match for that index for each location. Older PG versions are... flaky when it comes to optimization. I'm not sure if 8.1 used MAX as an internal construct or treated it like a function. If it's the latter, it has to read every value to find out which is the "max", which is why using ORDER BY *may* fix your problem. -- Shaun Thomas OptionsHouse | 141 W. Jackson Blvd. | Suite 800 | Chicago IL, 60604 312-676-8870 sthomas@peak6.com ______________________________________________ See http://www.peak6.com/email_disclaimer.php for terms and conditions related to this email