Re: Is there value in having optimizer stats for joins/foreignkeys?

From: Alexandra Wang <alexandra(dot)wang(dot)oss(at)gmail(dot)com>
To: Matheus Alcantara <matheusssilv97(at)gmail(dot)com>
Cc: Tomas Vondra <tomas(at)vondra(dot)me>, Corey Huinker <corey(dot)huinker(at)gmail(dot)com>, ilya(dot)evdokimov(at)tantorlabs(dot)com, jian he <jian(dot)universality(at)gmail(dot)com>, pgsql-hackers(at)lists(dot)postgresql(dot)org, Andrei Lepikhov <lepihov(at)gmail(dot)com>, Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>, hs(at)cybertec(dot)at, Jeff Davis <pgsql(at)j-davis(dot)com>
Subject: Re: Is there value in having optimizer stats for joins/foreignkeys?
Date: 2026-11-26 08:37:51
Message-ID: CAK98qZ2iJ2U9ifYFXFioKoQ7dWB_Vwk9K4r9T1G889HgLGq=ZA@mail.gmail.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

Hi Matheus,

Thanks a lot for the careful review and testing! Attached is v11,
the same four patches as v10, plus 0001 for REL_18_STABLE down to
REL_14_STABLE, named .nocfbot. My replies to your points are inline
below. Besides those, v11:

- caches the join conditions in the relcache with the other entries,
which makes planning on a table with 8 join statistics objects 26%
faster
- fixes several ways a join statistics object could fail to dump or
be re-created correctly: a dropped operator, a column named through
a join alias, a missing cast, and a 63-byte table name in a
self-join
- applies statistics targets as for single-table statistics, and
skips indexes that ANALYZE's snapshot cannot use yet

On Mon, Nov 23, 2026 Matheus Alcantara <matheusssilv97(at)gmail(dot)com> wrote:
> 0001
> ----
>
> Looks good to me. FWIW the same code (and XXX comment) is also present
> on the older branches. The patch applies cleanly to REL_19_STABLE, but
> not to REL_18_STABLE and older, where the context line still has a
> "(Datum) datum" cast, so we will need a different patch for older
> branches.

Thanks for checking the back branches. The leak goes back to
REL_14_STABLE, where expressions in extended statistics were added.
The attached back-branch patch differs from 0001 only in that context
line, and both pass make check on their branches.

> 0002
> ----
>
> [...]
>
> 1) Planning regression: to your question, I think caching the parsed
> list in the relcache is necessary. On optimized builds I see numbers
> similar to yours, about -16% tps with 8 column-only statistics objects
> and -9% with 8 (column, expression) objects.
>
> Another minor comment: the list is also run through
eval_const_expressions()
> twice on this path (with a NULL root in statext_get_stxexprs() and again
in
> plancat.c). That's cheap compared to the parsing, but the first pass seems
> unnecessary for the planner, or am I missing something?

Thanks, agreed. v11 caches the parsed entries of each statistics
object in its relation's relcache entry, in the new
RelationGetStatExtExprs(). With the pgbench test from my previous
mail (EXPLAIN only, -c1, optimized builds, median of 5 runs), v11 is
on par with master for 8 column-only statistics objects, and about
19% more tps for 8 (column, expression) objects, since master parses
those on every planning as well.

On running through eval_const_expressions() twice, you're not missing
anything. 0002 made one helper, statext_get_stxexprs(), serve ANALYZE,
statistics import and the planner. It does what ANALYZE needs,
including a pass with a NULL root, since ANALYZE has no planner
context, and the planner kept its own pass with the real root after
fixing the varnos. With the cache, the NULL-root pass runs only when
the entries are first cached, so it no longer runs on every planning.

> 2) pg_get_statisticsobjdef_columns() changes its return type from text
> to text[] while keeping the same OID, so an older psql running \d
> against a patched server prints:
>
> "public.z2_e" ON {a,"(b + 1)"} FROM z2
>
> This could also break user scripts that call the function. I'm wondering
> if we should add a new function rather than change the existing one.

Good catch! As you suggested, v11 changed
pg_get_statisticsobjdef_columns() back, and pg_stats_ext now gets an
array of stats entries from a new function,
pg_get_statisticsobjdef_columns_array().

Your comment also led me to the same problem in 0004, which added a
show_prefix argument to pg_get_statisticsobjdef() in place. Anything
naming pg_get_statisticsobjdef(oid) no longer found it, for example a
dump from 19 with REVOKE EXECUTE on that function failed to restore.
In v11 pg_get_statisticsobjdef() is the same as on master, and psql
gets the definition after "ON" from a new function,
pg_get_statisticsobjdef_body().

> 0003
> ----
>
> Looks good to me.

Thanks!

> 0004
> ----
>
> 1) Wrong estimate with self-joins: join_mcv_pair_selectivities() checks
> the other side with list_member_oid(stat->joinrels, other_reloid), which
> also matches the anchor's own OID, and then join conditions and filters
> are matched by attnum only. So a statistics object on t1 JOIN t2 is
> applied to a t1 self-join:
>
> [...]
>
> I think we need to map each planner rel to a stat position and require
> joinrels[pos] to match the RTE relid on both sides.

Good catch, thanks! Fixed. As you suggested, now each relation
must match the table at its position in the statistics object.

While I was here, I also added more test coverage for self-joins.

> 2) Inheritance: v10 rejects tables with inheritance children, but
> children can be added later. The planner never compares stat->inherit
> with rte->inh, and statext_mcv_load() is called with inh=false
> unconditionally. If the stats were built when the anchor had no
> children and a child is added later, ANALYZE skips the object with a
> WARNING but keeps the old data, which is then applied to the appendrel:
>
> [...]

Good catch, thanks! Fixed. The planner now compares stat->inherit
with rte->inh, as for single-table statistics, here for both tables.

> 3) Collations: I didn't reproduce this one, I just found it by reading
> the code, but find_index_for_operator() doesn't look at
> rd_indcollation. With a nondeterministic collation on the join
> condition and only a COLLATE "C" index on the probed column, the probes
> would only find exact matches and bias the sample. This make sense?

Yes, it does. I reproduced it with a case-insensitive ICU collation
and a COLLATE "C" index, which missed the 'ABC' rows. Fixed. An index
is now used only if it has the join condition's collation, as the
planner requires for index scans. I added a test to collate.icu.utf8.

> 4) A virtual generated column in the join condition is accepted, and
ANALYZE
> then silently produces no MCV data at all. Using the same column in the
> statistics column list is rejected, so I think we should also reject
virtual
> generated columns in the join condition.

Good catch, thanks! Fixed. CREATE STATISTICS now rejects a virtual
generated column in the join condition, with the same error as in
the column list. Both now name the column in a detail. I added the
case to the existing test.

> 5) lock_join_stats_rels() in parse_utilcmd.c takes
> ShareUpdateExclusiveLock on the referenced tables before the permission
> check. So a user with only SELECT on someone else's table t2 can do
>
> begin;
> create statistics ... from t join t2 on ...;
> -- keep the transaction open
>
> and block VACUUM, ANALYZE and CREATE INDEX on t2, and make autovacuum
> skip it, while the same user's LOCK TABLE t2 IN SHARE UPDATE EXCLUSIVE
> MODE is denied. I'm wondering if the non-anchor tables only need
> AccessShareLock, and the permission check should happen before locking
> (RangeVarGetRelidExtended() with a callback).

Good catch, thanks! Fixed. The other tables now get only the
AccessShareLock a query takes, as CREATE TABLE ... LIKE does for the
table it reads. While fixing it, I noticed that v10 looked them up
and locked them twice, in lock_join_stats_rels() and again in
transformFromClause(). So lock_join_stats_rels() is gone, and
transformFromClause() takes that lock alone. Only the anchor is
still locked beforehand, with the ShareUpdateExclusiveLock that
single-table statistics take. A new isolation test covers it.

As the other tables are now locked as in a query, I didn't add the
callback. A user without SELECT waits only if another session holds
ACCESS EXCLUSIVE on the table, as their own SELECT would. Does that
sound OK to you?

> 6) A permanent statistics object can reference a temp table. While the
> session owning the temp table is alive, ANALYZE of the anchor in any
> other session fails with "cannot access temporary tables of other
> sessions".

Good catch, thanks! Fixed. Statistics on a table that is not
temporary can no longer join a temporary table, as a permanent table
cannot inherit from a temporary one, and no statistics can join a
temporary table of another session. Statistics on a temporary table
may still join permanent tables, since only its own session analyzes
it. I added a test, also with a join of three tables.

> 7) If the other table belongs to another user, the statistics owner
> can't see their own data in pg_stats_ext, because the view requires
> pg_has_role(USAGE) on the owner of every joined table, while CREATE
> STATISTICS and ANALYZE only require SELECT on the non-anchor tables.
> Since pg_dump reads the data from that view, a dump taken by the
> statistics owner silently omits it.

Good catch, thanks! Fixed. pg_stats_ext now shows join statistics
to a user who owns the anchor, as before, and has SELECT on the
other tables, which is what CREATE STATISTICS requires of their
owner. So the owner sees their own data, and their dump includes
it. The anchor keeps the owner check that single-table statistics
have, and the row-level security check is unchanged. I extended the
test with two owners for it.

This also raises what should happen when the owner later loses
SELECT on another table. In v11 the statistics object stays, and
ALTER COLUMN TYPE re-creates it as it does any statistics. ANALYZE
skips it with a warning and keeps the existing data, which the
planner still uses. REFRESH MATERIALIZED VIEW does the same when
the view's owner loses SELECT on a table it reads: it fails and
keeps the contents. As pg_stats_ext checks the user reading it, the
data is no longer shown to the owner, as pg_stats hides a column's
statistics once its reader loses SELECT on it. Does that sound
right to you?

> 8) "ON ca.*" reports "statistics creation on system columns is not
> supported".

Thanks for spotting it. Single-table statistics give the same
message for ON (t.*), as the check for system columns also catches
whole-row references. As it is not specific to join statistics, I
left it alone in v11. If others think the message is worth fixing,
I'm happy to add a separate patch for it to the series.

Best,
Alex

Attachment Content-Type Size
v11-0001-Fix-memory-leak-in-make_build_data.patch application/octet-stream 1.6 KB
v11-0001-REL_18-REL_14.patch.nocfbot application/octet-stream 1.6 KB
v11-0003-Improve-auto-generated-names-for-extended-statis.patch application/octet-stream 6.0 KB
v11-0004-Add-join-MCV-statistics-for-selectivity-estimati.patch application/octet-stream 440.2 KB
v11-0002-Unify-extended-statistics-columns-and-expression.patch application/octet-stream 139.3 KB

In response to

Browse pgsql-hackers by date

  From Date Subject
Next Message Peter Eisentraut 2026-11-26 08:44:50 Re: Don't use the deprecated and insecure PQcancel in our frontend tools anymore
Previous Message Hayato Kuroda (Fujitsu) 2026-11-26 08:12:24 RE: Proposal: Conflict log history table for Logical Replication