Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA384:256) (Exim 4.89) (envelope-from ) id 1ehGMO-0001Ve-Rl for pgsql-performance@arkaria.postgresql.org; Thu, 01 Feb 2018 15:01:08 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.84_2) (envelope-from ) id 1ehGMN-0000FM-TH for pgsql-performance@arkaria.postgresql.org; Thu, 01 Feb 2018 15:01:07 +0000 Received: from magus.postgresql.org ([2a02:c0:301:0:ffff::29]) by malur.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA384:256) (Exim 4.84_2) (envelope-from ) id 1ehGMN-0000F5-Lf for pgsql-performance@lists.postgresql.org; Thu, 01 Feb 2018 15:01:07 +0000 Received: from sss.pgh.pa.us ([66.207.139.130]) by magus.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA384:256) (Exim 4.89) (envelope-from ) id 1ehGM5-0006iX-TU for pgsql-performance@lists.postgresql.org; Thu, 01 Feb 2018 15:01:06 +0000 Received: from sss1.sss.pgh.pa.us (localhost [127.0.0.1]) by sss.pgh.pa.us (8.14.4/8.14.4) with ESMTP id w11F0feP023736; Thu, 1 Feb 2018 10:00:41 -0500 From: Tom Lane To: Johan Fredriksson cc: pgsql-performance@lists.postgresql.org Subject: Re: bad plan using nested loops In-reply-to: <1517481727.23675.3.camel@kth.se> References: <1517481727.23675.3.camel@kth.se> Comments: In-reply-to Johan Fredriksson message dated "Thu, 01 Feb 2018 11:42:07 +0100" MIME-Version: 1.0 Content-Type: text/plain; charset="us-ascii" Content-ID: <23734.1517497241.1@sss.pgh.pa.us> Content-Transfer-Encoding: quoted-printable Date: Thu, 01 Feb 2018 10:00:41 -0500 Message-ID: <23735.1517497241@sss.pgh.pa.us> List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Precedence: bulk Johan Fredriksson writes: > Bad plan: https://explain.depesz.com/s/avtZ > Good plan: https://explain.depesz.com/s/SJSt > Any suggestions on how to make the planner make better decisions for > this query? Core of the problem looks to be the misestimation here: Index Only Scan using shredder_cgm1 on public.cachedgroupmembers cachedgr= oupmembers_4 (cost=3D0.43..2.33 rows=3D79 width=3D8) (actual time=3D0.020.= .0.903 rows=3D1492 loops=3D804) Output: cachedgroupmembers_4.memberid, cachedgroupmembers_4.groupid, ca= chedgroupmembers_4.disabled Index Cond: ((cachedgroupmembers_4.memberid =3D principals_1.id) AND (c= achedgroupmembers_4.disabled =3D 0)) Heap Fetches: 5018 Probably, memberid and disabled are correlated but the planner doesn't know that, so it thinks the index condition is way more selective than it actually is. In PG 10, you could very possibly fix that by installing extended statistics on that pair of columns. See https://www.postgresql.org/docs/current/static/planner-stats.html#PLANNER-= STATS-EXTENDED regards, tom lane