Received: from maia.hub.org (maia-3.hub.org [200.46.204.243]) by mail.postgresql.org (Postfix) with ESMTP id 287971336B42 for ; Mon, 24 Jan 2011 16:07:46 -0400 (AST) Received: from mail.postgresql.org ([200.46.204.86]) by maia.hub.org (mx1.hub.org [200.46.204.243]) (amavisd-maia, port 10024) with ESMTP id 05386-04 for ; Mon, 24 Jan 2011 20:07:38 +0000 (UTC) X-Greylist: from auto-whitelisted by SQLgrey-1.7.6 Received: from depesz.com (martin.depesz.com [188.40.39.14]) by mail.postgresql.org (Postfix) with ESMTP id AD7FC1337B7A for ; Mon, 24 Jan 2011 16:07:38 -0400 (AST) Received: from martin.depesz.com ([188.40.39.14] helo=depesz.com) by depesz.com with esmtpa (Exim 4.69) (envelope-from ) id 1PhShM-0006vD-60; Mon, 24 Jan 2011 21:07:36 +0100 Date: Mon, 24 Jan 2011 21:07:36 +0100 From: hubert depesz lubaczewski To: Dimi Paun Cc: "pgsql-performance@postgresql.org" Subject: Re: How to use indexes for GROUP BY Message-ID: <20110124200735.GA23732@depesz.com> Reply-To: depesz@depesz.com References: <1295893741.9380.984.camel@dimi.lattica.com> MIME-Version: 1.0 Content-Type: text/plain; charset=utf-8 Content-Disposition: inline In-Reply-To: <1295893741.9380.984.camel@dimi.lattica.com> User-Agent: Mutt/1.5.21 (2010-09-15) X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=-1.91 tagged_above=-10 required=5 tests=BAYES_00=-1.9, T_RP_MATCHES_RCVD=-0.01 X-Spam-Level: X-Archive-Number: 201101/223 X-Sequence-Number: 42010 On Mon, Jan 24, 2011 at 01:29:01PM -0500, Dimi Paun wrote: > Hi folks, > > I have a table like so: > > create table tagRecord ( > uid varchar(60) primary key, > [bunch of other fields] > location varchar(32), > creationTS timestamp > ); > create index idx_tagdata_loc_creationTS on tagRecord(location, creationTS); > > The number of individual values in location is small (e.g. 2). > > 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; > QUERY PLAN > ------------------------------------------------------------------------------------------------------------------------- > HashAggregate (cost=5330.53..5330.55 rows=2 width=18) (actual time=286.161..286.165 rows=3 loops=1) > -> Seq Scan on tagrecord (cost=0.00..4771.35 rows=111835 width=18) (actual time=0.059..119.828 rows=111739 loops=1) > Total runtime: 286.222 ms you can use technique described in here: http://www.depesz.com/index.php/2009/07/10/getting-list-of-unique-elements/ Best regards, depesz