Received: from maia.hub.org (maia-5.hub.org [200.46.204.29]) by mail.postgresql.org (Postfix) with ESMTP id 37E96133616B for ; Mon, 24 Jan 2011 15:01:58 -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 89275-08 for ; Mon, 24 Jan 2011 19:01:51 +0000 (UTC) X-Greylist: delayed 00:32:35.946598 by SQLgrey-1.7.6 Received: from ulysses.lattica.com (lattica.com [204.14.19.114]) by mail.postgresql.org (Postfix) with ESMTP id 5532D13364DE for ; Mon, 24 Jan 2011 15:01:50 -0400 (AST) Received: from localhost (ulysses.lattica.com [127.0.0.1]) by ulysses.lattica.com (Postfix) with ESMTP id 0E1ACEA4004 for ; Mon, 24 Jan 2011 13:29:12 -0500 (EST) X-Virus-Scanned: amavisd-new at lattica.com Received: from ulysses.lattica.com ([127.0.0.1]) by localhost (ulysses.lattica.com [127.0.0.1]) (amavisd-new, port 10024) with ESMTP id ztTKsZYZtteR for ; Mon, 24 Jan 2011 13:29:01 -0500 (EST) Received: from [192.168.3.11] (CPE00104b0b2be4-CM00222d5a2acd.cpe.net.cable.rogers.com [99.255.186.187]) by ulysses.lattica.com (Postfix) with ESMTP id B1307EA4001 for ; Mon, 24 Jan 2011 13:29:01 -0500 (EST) Subject: How to use indexes for GROUP BY From: Dimi Paun To: "pgsql-performance@postgresql.org" Content-Type: text/plain; charset="UTF-8" Organization: Lattica, Inc. Date: Mon, 24 Jan 2011 13:29:01 -0500 Message-ID: <1295893741.9380.984.camel@dimi.lattica.com> Mime-Version: 1.0 X-Mailer: Evolution 2.32.1 (2.32.1-1.fc14) Content-Transfer-Encoding: 7bit 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/220 X-Sequence-Number: 42007 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 Now I have the idx_tagdata_loc_creationTS, and it seemed to me that it should be able to use it to quickly figure out the max creationTS for each location. Any way I can make this more efficient? BTW, I am using postgresql-server-8.1.22-1.el5_5.1 -- Dimi Paun Lattica, Inc.