Received: from localhost (unknown [200.46.204.183]) by postgresql.org (Postfix) with ESMTP id D34C59FA277 for ; Fri, 2 Nov 2007 04:56:10 -0300 (ADT) Received: from postgresql.org ([200.46.204.71]) by localhost (mx1.hub.org [200.46.204.183]) (amavisd-maia, port 10024) with ESMTP id 20775-03 for ; Fri, 2 Nov 2007 04:56:08 -0300 (ADT) X-Greylist: from auto-whitelisted by SQLgrey-1.7.5 Received: from depesz.com (depesz.com [88.198.37.40]) by postgresql.org (Postfix) with ESMTP id 120619FA271 for ; Fri, 2 Nov 2007 04:56:06 -0300 (ADT) Received: from depesz by depesz.com with local (Exim 4.63) (envelope-from ) id 1InrNs-0004OV-6x; Fri, 02 Nov 2007 08:56:04 +0100 Date: Fri, 2 Nov 2007 08:56:04 +0100 From: hubert depesz lubaczewski To: Palle Girgensohn Cc: pgsql-performance@postgresql.org Subject: Re: select max(field) from table much faster with a group by clause? Message-ID: <20071102075604.GA16757@depesz.com> Reply-To: depesz@depesz.com References: MIME-Version: 1.0 Content-Type: text/plain; charset=utf-8 Content-Disposition: inline In-Reply-To: User-Agent: Mutt/1.5.13 (2006-08-11) X-Virus-Scanned: Maia Mailguard 1.0.1 X-Archive-Number: 200711/30 X-Sequence-Number: 27445 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)