Received: from maia.hub.org (maia-5.hub.org [200.46.204.29]) by mail.postgresql.org (Postfix) with ESMTP id ED347B5DBF3 for ; Tue, 12 Jul 2011 17:04:21 -0300 (ADT) Received: from mail.postgresql.org ([200.46.204.86]) by maia.hub.org (mx1.hub.org [200.46.204.29]) (amavisd-maia, port 10024) with ESMTP id 58585-04 for ; Tue, 12 Jul 2011 20:04:16 +0000 (UTC) X-Greylist: from auto-whitelisted by SQLgrey-1.7.6 Received: from sss.pgh.pa.us (sss.pgh.pa.us [66.207.139.130]) by mail.postgresql.org (Postfix) with ESMTP id CCC42B5DBEF for ; Tue, 12 Jul 2011 17:04:15 -0300 (ADT) Received: from sss2.sss.pgh.pa.us (tgl@localhost [127.0.0.1]) by sss.pgh.pa.us (8.14.2/8.14.2) with ESMTP id p6CK4CdF004627; Tue, 12 Jul 2011 16:04:13 -0400 (EDT) To: Mario Splivalo cc: pgsql-performance@postgresql.org Subject: Re: Planner choosing NestedLoop, although it is slower... In-reply-to: <4E1C8E62.2090800@megafon.hr> References: <4E1C8E62.2090800@megafon.hr> Comments: In-reply-to Mario Splivalo message dated "Tue, 12 Jul 2011 20:11:46 +0200" Date: Tue, 12 Jul 2011 16:04:12 -0400 Message-ID: <4626.1310501052@sss.pgh.pa.us> From: Tom Lane X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=-1.91 tagged_above=-10 required=5 tests=BAYES_00=-1.9, T_RP_MATCHES_RCVD=-0.01 X-Spam-Level: X-Archive-Number: 201107/118 X-Sequence-Number: 44330 Mario Splivalo writes: > Limit (cost=0.00..415.91 rows=21 width=8) (actual > time=11263.089..11263.089 rows=0 loops=1) > -> Nested Loop (cost=0.00..186249.55 rows=9404 width=8) (actual > time=11263.087..11263.087 rows=0 loops=1) > Why is planner using NestedLoops, Because it thinks the LIMIT will kick in and end the query when the join is only 21/9404ths (ie, a fraction of a percent) complete. A NestLoop results in saving a lot of work in that situation, whereas hash-and-sort has to do the whole join despite the LIMIT. What you need to look into is why the estimated join size is 9400 rows when the actual join size is zero. Are both tables ANALYZEd? Are you intentionally selecting rows that have no join partners? regards, tom lane