Received: from localhost (unknown [200.46.204.187]) by postgresql.org (Postfix) with ESMTP id DEBA59F9D56 for ; Thu, 27 Sep 2007 11:40:38 -0300 (ADT) Received: from postgresql.org ([200.46.204.71]) by localhost (mx1.hub.org [200.46.204.187]) (amavisd-maia, port 10024) with ESMTP id 77361-07 for ; Thu, 27 Sep 2007 11:40:26 -0300 (ADT) X-Greylist: from auto-whitelisted by SQLgrey-1.7.5 Received: from sss.pgh.pa.us (sss.pgh.pa.us [66.207.139.130]) by postgresql.org (Postfix) with ESMTP id 714DD9F9ADC for ; Thu, 27 Sep 2007 11:40:32 -0300 (ADT) Received: from sss2.sss.pgh.pa.us (tgl@localhost [127.0.0.1]) by sss.pgh.pa.us (8.14.1/8.14.1) with ESMTP id l8REeQeO029187; Thu, 27 Sep 2007 10:40:26 -0400 (EDT) To: Csaba Nagy cc: postgres performance list , Simon Riggs Subject: Re: Searching for the cause of a bad plan In-reply-to: <1190894004.5430.46.camel@PCD12478> References: <1190369024.4661.173.camel@PCD12478> <6175.1190390913@sss.pgh.pa.us> <1190396352.4202.109.camel@ebony.site> <13644.1190397220@sss.pgh.pa.us> <1190399879.4202.127.camel@ebony.site> <27857.1190417434@sss.pgh.pa.us> <1190640429.4181.165.camel@ebony.site> <1190818357.5430.29.camel@PCD12478> <21582.1190820137@sss.pgh.pa.us> <1190894004.5430.46.camel@PCD12478> Comments: In-reply-to Csaba Nagy message dated "Thu, 27 Sep 2007 13:53:24 +0200" Date: Thu, 27 Sep 2007 10:40:25 -0400 Message-ID: <29186.1190904025@sss.pgh.pa.us> From: Tom Lane X-Virus-Scanned: Maia Mailguard 1.0.1 X-Archive-Number: 200709/456 X-Sequence-Number: 27001 Csaba Nagy writes: > On Wed, 2007-09-26 at 11:22 -0400, Tom Lane wrote: >> ... how >> many values of "a" are there really, and what's the true distribution of >> counts? > table_a has 23366 distinct values. Some statistics (using R): >> summary(table_a_histogram) > a count > Min. : 70000857 Min. : 1 > 1st Qu.:700003628 1st Qu.: 9 > Median :700011044 Median : 22 > Mean :622429573 Mean : 17640 > 3rd Qu.:700018020 3rd Qu.: 391 > Max. :800003349 Max. :3347707 Ugh, classic long-tail distribution. This is a really hard problem to solve by sampling --- the sample will naturally be biased towards the more common values, and so ANALYZE tends to conclude there are fewer distinct values than there really are. That means n_distinct in the stats is too small, and that feeds directly into the misestimation of the number of matching rows. And yet there's another trap here: if the parameter you passed in chanced to be one of the very common values, a plan that was optimized for a small number of matches would perform terribly. We've speculated about trying to deal with these types of situations by switching plans on-the-fly at runtime, but that's just blue-sky dreaming at the moment. In the short run, if boosting the stats target doesn't result in acceptable plans, there may be no real solution other than to avoid parameterized queries on this column. regards, tom lane