Received: from localhost (unknown [200.46.204.182]) by postgresql.org (Postfix) with ESMTP id C55539FB438 for ; Thu, 4 Oct 2007 15:14:22 -0300 (ADT) Received: from postgresql.org ([200.46.204.71]) by localhost (mx1.hub.org [200.46.204.182]) (amavisd-maia, port 10024) with ESMTP id 99496-01 for ; Thu, 4 Oct 2007 15:14:14 -0300 (ADT) X-Greylist: from auto-whitelisted by SQLgrey-1.7.5 Received: from mx00.pub.collaborativefusion.com (mx00.pub.collaborativefusion.com [206.210.89.199]) by postgresql.org (Postfix) with ESMTP id 1D2B39F9B40 for ; Thu, 4 Oct 2007 15:14:14 -0300 (ADT) Received: from vanquish.pitbpa0.priv.collaborativefusion.com (vanquish.pitbpa0.priv.collaborativefusion.com [192.168.2.61]) (SSL: TLSv1/SSLv3,256bits,AES256-SHA) by wingspan with esmtp; Thu, 04 Oct 2007 14:14:11 -0400 id 0005648D.47052D73.0000C5EB Date: Thu, 4 Oct 2007 14:14:11 -0400 From: Bill Moran To: Ben Cc: pgsql-performance@postgresql.org Subject: Re: quickly getting the top N rows Message-Id: <20071004141411.9509fe66.wmoran@collaborativefusion.com> In-Reply-To: References: Organization: Collaborative Fusion X-Mailer: Sylpheed 2.4.4 (GTK+ 2.10.14; i386-portbld-freebsd6.2) Mime-Version: 1.0 Content-Type: text/plain; charset=US-ASCII Content-Transfer-Encoding: 7bit X-Virus-Scanned: Maia Mailguard 1.0.1 X-Archive-Number: 200710/37 X-Sequence-Number: 27059 In response to Ben : > If I have this: > > create table foo (bar int primary key); > > ...then in my ideal world, Postgres would be able to use that index on bar > to help me with this: > > select bar from foo order by bar desc limit 20; > > But in my experience, PG8.2 is doing a full table scan on foo, then > sorting it, then doing the limit. I have a more complex primary key, but I > was hoping the same concept would still apply. Am I doing something wrong, > or just expecting something that doesn't exist? Show us the explain. However, 2 guesses: 1) You never analyzed the table, thus PG has awful statistics and doesn't know how to pick a good plan. 2) You have so few rows in the table that a seq scan is actually faster than an index scan, which is why PG uses it instead. -- Bill Moran Collaborative Fusion Inc. http://people.collaborativefusion.com/~wmoran/ wmoran@collaborativefusion.com Phone: 412-422-3463x4023