X-Original-To: pgsql-performance-postgresql.org@localhost.postgresql.org Received: from localhost (unknown [200.46.204.144]) by svr1.postgresql.org (Postfix) with ESMTP id CC7465E46CC for ; Sun, 29 Aug 2004 19:04:16 -0300 (ADT) Received: from svr1.postgresql.org ([200.46.204.71]) by localhost (av.hub.org [200.46.204.144]) (amavisd-new, port 10024) with ESMTP id 60274-05 for ; Sun, 29 Aug 2004 22:04:14 +0000 (GMT) Received: from trofast.sesse.net (trofast.sesse.net [129.241.93.32]) by svr1.postgresql.org (Postfix) with ESMTP id A145D5E46C2 for ; Sun, 29 Aug 2004 19:04:11 -0300 (ADT) Received: from sesse by trofast.sesse.net with local (Exim 3.36 #1 (Debian)) id 1C1XmX-0000OK-00 for ; Mon, 30 Aug 2004 00:04:13 +0200 Date: Mon, 30 Aug 2004 00:04:13 +0200 From: "Steinar H. Gunderson" To: pgsql-performance@postgresql.org Subject: Re: Why does a simple query not use an obvious index? Message-ID: <20040829220413.GA1490@uio.no> References: <1093804128.5493.22.camel@localhost.localdomain> <87fz65k5sq.fsf@stark.xeocode.com> <1093815480.5493.29.camel@localhost.localdomain> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline In-Reply-To: <1093815480.5493.29.camel@localhost.localdomain> User-Agent: Mutt/1.5.6+20040818i X-Virus-Scanned: by amavisd-new at hub.org X-Spam-Status: No, hits=0.0 tagged_above=0.0 required=5.0 tests= X-Spam-Level: X-Archive-Number: 200408/433 X-Sequence-Number: 8069 On Sun, Aug 29, 2004 at 03:38:00PM -0600, Scott Marlowe wrote: >>> select somefield from sometable where timestampfield > now()-'60 >>> seconds'::interval >>> >>> and count the number of returned rows. If there's a lot, it won't be >>> any faster, if there's a few, it should be a win. >> Why would this ever be faster? And how could postgres ever calculate that >> without doing a sequential scan when count(*) would force it to do a >> sequential scan? > Because, count(*) CANNOT use an index. So, if you're hitting, say, > 0.01% of the table (let's say 20 out of 20,000,000 rows or something > like that) then the second should be MUCH faster. Of course count(*) can use an index: images=# explain analyze select count(*) from images where event='test'; QUERY PLAN ------------------------------------------------------------------------------------------------------------------------------------ Aggregate (cost=168.97..168.97 rows=1 width=0) (actual time=68.211..68.215 rows=1 loops=1) -> Index Scan using unique_filenames on images (cost=0.00..168.81 rows=63 width=0) (actual time=68.094..68.149 rows=8 loops=1) Index Cond: ((event)::text = 'test'::text) Total runtime: 68.369 ms (4 rows) However, it cannot rely on an index _alone_; it has to go fetch the relevant pages, but of course, so must "select somefield from" etc.. /* Steinar */ -- Homepage: http://www.sesse.net/