pg.ddx.io  pgsql-performance@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: hubert depesz lubaczewski <depesz@depesz.com>
To: Palle Girgensohn <girgen@pingpong.net>
Cc: pgsql-performance@postgresql.org
Subject: Re: select max(field) from table much faster with a group by clause?
Date: Fri, 2 Nov 2007 08:56:04 +0100
Message-ID: <20071102075604.GA16757@depesz.com> (raw)
In-Reply-To: <D26563C7B9CCEB0A338FF08E@rambutan.pingpong.net>
References: <D26563C7B9CCEB0A338FF08E@rambutan.pingpong.net>

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)



view thread (11+ messages)  latest in thread

Message-ID: <20071102075604.GA16757@depesz.com>
Permalink:  ../20071102075604.GA16757@depesz.com/
Also on:    postgresql.org/message-id/20071102075604.GA16757@depesz.com

 · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients using the --to and --cc options:
  reply via email

  To: pgsql-performance@postgresql.org
  Cc: depesz@depesz.com, girgen@pingpong.net
  Subject: Re: select max(field) from table much faster with a group by clause?
  In-Reply-To: <20071102075604.GA16757@depesz.com>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox