Re: select max(field) from table much faster with a group by clause? - Mailing list pgsql-performance

From hubert depesz lubaczewski
Subject Re: select max(field) from table much faster with a group by clause?
Date
Msg-id 20071102075604.GA16757@depesz.com
Whole thread Raw
In response to select max(field) from table much faster with a group by clause?  (Palle Girgensohn <girgen@pingpong.net>)
List pgsql-performance
On Thu, Nov 01, 2007 at 02:07:55PM +0100, Palle Girgensohn wrote:
> I have a table "login" with approx 600,000 tuples, a person table with
> approx 100000 tuples.
> When running
> select max("when") from login where userid='userid'
> it takes a second or two, but when adding "group by userid" the planner
> decides on using another plan, and it gets *much* faster. See example below.
> pp=# explain analyze SELECT max("when") FROM login WHERE userid='girgen' ;

just do:
create index q on login (userid, "when"); and you should be fine.
if it will not help, rewrite the query as:
select "when"
from login
where userid = 'girgen'
order by userid desc, "when" desc limit 1;

depesz

--
quicksil1er: "postgres is excellent, but like any DB it requires a
highly paid DBA.  here's my CV!" :)
http://www.depesz.com/ - blog dla ciebie (i moje CV)

pgsql-performance by date:

Previous
From: "Carlo Stonebanks"
Date:
Subject: Re: How to avoid hashjoin and mergejoin
Next
From: Jens-Wolfhard Schicke
Date:
Subject: Unfortunate expansion of composite types in union