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 95FE6564DC for ; Tue, 8 Mar 2005 07:03:47 +0000 (GMT) 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 66244-05 for ; Tue, 8 Mar 2005 07:03:46 +0000 (GMT) Received: from megazone.bigpanda.com (megazone.bigpanda.com [64.147.171.210]) by svr1.postgresql.org (Postfix) with ESMTP id 207FD564B6 for ; Tue, 8 Mar 2005 07:03:45 +0000 (GMT) Received: by megazone.bigpanda.com (Postfix, from userid 1001) id B7DFF353A4; Mon, 7 Mar 2005 23:03:43 -0800 (PST) Received: from localhost (localhost [127.0.0.1]) by megazone.bigpanda.com (Postfix) with ESMTP id B650F353A0; Mon, 7 Mar 2005 23:03:43 -0800 (PST) Date: Mon, 7 Mar 2005 23:03:43 -0800 (PST) From: Stephan Szabo To: Michael McFarland Cc: pgsql-performance@postgresql.org Subject: Re: adding 'limit' leads to very slow query In-Reply-To: Message-ID: <20050307230123.L97147@megazone.bigpanda.com> References: MIME-Version: 1.0 Content-Type: TEXT/PLAIN; charset=US-ASCII X-Virus-Scanned: by amavisd-new at hub.org X-Spam-Status: No, hits=0.005 tagged_above=0 required=5 tests=AWL X-Spam-Level: X-Archive-Number: 200503/120 X-Sequence-Number: 10825 On Mon, 7 Mar 2005, Michael McFarland wrote: > I'm trying to understand why a particular query is slow, and it seems > like the optimizer is choosing a strange plan. See this summary: > > > * I have a large table, with an index on the primary key 'id' and on a > field 'foo'. > > select count(*) from foo; > 1,000,000 > > select count(*) from foo where bar = 41; > 7 > > * This query happens very quickly. > > explain select * from foo where barId = 412 order by id desc; > Sort () > Sort key= id > -> Index scan using bar_index on foo () > Index cond: barId = 412 > > But this query takes forever > > > explain select * from foo where barId = 412 order by id desc limit 25; > Limit () > -> Index scan backward using primarykey_index > Filter: barID = 412 You didn't show the row estimates, but I'd guess that it's expecting either that ther are more rows that match barId=412 than there actually are (which may be solvable by raising the statistics target on the column and re-analyzing) such that going backwards on id in order to make 25 matching rows isn't a bad plan or that barId and id are correlated which is unfortunately not going to be recognized right now.