Received: from maia.hub.org (maia-3.hub.org [200.46.204.243]) by mail.postgresql.org (Postfix) with ESMTP id 1E418B5DBC1 for ; Fri, 1 Jul 2011 19:47:01 -0300 (ADT) Received: from mail.postgresql.org ([200.46.204.86]) by maia.hub.org (mx1.hub.org [200.46.204.243]) (amavisd-maia, port 10024) with ESMTP id 01687-03 for ; Fri, 1 Jul 2011 22:46:50 +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 5C78EB5DBD0 for ; Fri, 1 Jul 2011 19:46:50 -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 p61Mknq8006961; Fri, 1 Jul 2011 18:46:49 -0400 (EDT) To: Samuel Gendler cc: pgsql-performance@postgresql.org Subject: Re: near identical queries have vastly different plans In-reply-to: References: Comments: In-reply-to Samuel Gendler message dated "Thu, 30 Jun 2011 01:53:14 -0700" Date: Fri, 01 Jul 2011 18:46:49 -0400 Message-ID: <6960.1309560409@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/5 X-Sequence-Number: 44217 Samuel Gendler writes: > I've got 2 nearly identical queries that perform incredibly differently. The reason the slow query sucks is that the planner is estimating at most one "s" row will match that complicated AND/OR condition, so it goes for a nestloop. In the "fast" query there is another complicated AND/OR filter condition, but it's not so far off on the number of matching rows, so you get a better plan choice. Can't tell from the given information whether the better guess is pure luck, or there's some difference in the column statistics that makes it able to get a better estimate for that. In general, though, you're skating on thin ice anytime you ask the planner to derive statistical estimates about combinations of correlated columns --- and these evidently are correlated. Think about refactoring the table definitions so that you're only testing a single column, which ANALYZE will be able to provide stats about. Or maybe you can express it as a test on a computed expression, which you could then keep an index on, prompting ANALYZE to gather stats about that. regards, tom lane