pgsql: Fix misestimation of n_distinct for a nearly-unique column with - Mailing list pgsql-committers

From Tom Lane
Subject pgsql: Fix misestimation of n_distinct for a nearly-unique column with
Date
Msg-id E1bWWvh-000075-Pk@gemulon.postgresql.org
Whole thread Raw
List pgsql-committers
Fix misestimation of n_distinct for a nearly-unique column with many nulls.

If ANALYZE found no repeated non-null entries in its sample, it set the
column's stadistinct value to -1.0, intending to indicate that the entries
are all distinct.  But what this value actually means is that the number
of distinct values is 100% of the table's rowcount, and thus it was
overestimating the number of distinct values by however many nulls there
are.  This could lead to very poor selectivity estimates, as for example
in a recent report from Andreas Joseph Krogh.  We should discount the
stadistinct value by whatever we've estimated the nulls fraction to be.
(That is what will happen if we choose to use a negative stadistinct for
a column that does have repeated entries, so this code path was just
inconsistent.)

In addition to fixing the stadistinct entries stored by several different
ANALYZE code paths, adjust the logic where get_variable_numdistinct()
forces an "all distinct" estimate on the basis of finding a relevant unique
index.  Unique indexes don't reject nulls, so there's no reason to assume
that the null fraction doesn't apply.

Back-patch to all supported branches.  Back-patching is a bit of a judgment
call, but this problem seems to affect only a few users (else we'd have
identified it long ago), and it's bad enough when it does happen that
destabilizing plan choices in a worse direction seems unlikely.

Patch by me, with documentation wording suggested by Dean Rasheed

Report: <VisenaEmail.26.df42f82acae38a58.156463942b8@tc7-visena>
Discussion: <16143.1470350371@sss.pgh.pa.us>

Branch
------
master

Details
-------
http://git.postgresql.org/pg/commitdiff/95bee941be4c009ebbc29162a0dc9664f40de12f

Modified Files
--------------
doc/src/sgml/catalogs.sgml                    |  6 +++---
src/backend/commands/analyze.c                | 16 +++++++++++-----
src/backend/tsearch/ts_typanalyze.c           |  2 +-
src/backend/utils/adt/rangetypes_typanalyze.c |  4 +++-
src/backend/utils/adt/selfuncs.c              | 12 ++++++++----
src/include/catalog/pg_statistic.h            | 15 ++++++++-------
6 files changed, 34 insertions(+), 21 deletions(-)


pgsql-committers by date:

Previous
From: Tom Lane
Date:
Subject: pgsql: Fix misestimation of n_distinct for a nearly-unique column with
Next
From: Tom Lane
Date:
Subject: pgsql: Fix misestimation of n_distinct for a nearly-unique column with