Received: from localhost (unknown [200.46.204.183]) by postgresql.org (Postfix) with ESMTP id C581164FCCA for ; Fri, 19 Sep 2008 15:25:35 -0300 (ADT) Received: from postgresql.org ([200.46.204.86]) by localhost (mx1.hub.org [200.46.204.183]) (amavisd-maia, port 10024) with ESMTP id 06913-06 for ; Fri, 19 Sep 2008 15:25:31 -0300 (ADT) X-Greylist: from auto-whitelisted by SQLgrey-1.7.6 Received: from mail-gx0-f17.google.com (mail-gx0-f17.google.com [209.85.217.17]) by postgresql.org (Postfix) with ESMTP id 1798064FCC2 for ; Fri, 19 Sep 2008 15:25:31 -0300 (ADT) Received: by gxk10 with SMTP id 10so1006328gxk.19 for ; Fri, 19 Sep 2008 11:25:30 -0700 (PDT) Received: by 10.142.174.8 with SMTP id w8mr165646wfe.33.1221848729893; Fri, 19 Sep 2008 11:25:29 -0700 (PDT) Received: from ?10.10.30.141? ( [204.11.227.33]) by mx.google.com with ESMTPS id 30sm2431151wff.18.2008.09.19.11.25.29 (version=SSLv3 cipher=RC4-MD5); Fri, 19 Sep 2008 11:25:29 -0700 (PDT) Subject: Re: why does this use the wrong index? From: Jeff Davis To: Rainer Mager Cc: pgsql-performance@postgresql.org In-Reply-To: <000101c919ef$7c0b8e20$7422aa60$@com> References: <000101c919ef$7c0b8e20$7422aa60$@com> Content-Type: text/plain Date: Fri, 19 Sep 2008 11:25:28 -0700 Message-Id: <1221848728.6194.292.camel@dell.linuxdev.us.dell.com> Mime-Version: 1.0 X-Mailer: Evolution 2.22.3.1 Content-Transfer-Encoding: 7bit X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=0 tagged_above=0 required=5 tests=none X-Spam-Level: X-Archive-Number: 200809/193 X-Sequence-Number: 31506 > So, What can I do to encourage Postgres to use the first index even when the > date range is smaller. > It looks like PostgreSQL is estimating the selectivity of your date ranges poorly. In the second (bad) plan it estimates that the index scan with the filter will return 1 row (and that's probably because it estimates that the date range you specify will match only one row). This leads PostgreSQL to choose the narrower index because, if the index scan is only going to return one row anyway, it might as well scan the smaller index. What's the n_distinct for start_time? => select n_distinct from pg_stats where tablename='ad_log' and attname='start_time'; If n_distinct is near -1, that would explain why it thinks that it will only get one result. Based on the difference between the good index scan (takes 0.056ms per loop) and the bad index scan with the filter (311ms per loop), the "player" condition must be very selective, but PostgreSQL doesn't care because it already thinks that the date range is selective. Regards, Jeff Davis