Have the planner replace COUNT(ANY) with COUNT(*), when possible
authorDavid Rowley <drowley@postgresql.org>
Wed, 26 Nov 2025 21:43:28 +0000 (10:43 +1300)
committerDavid Rowley <drowley@postgresql.org>
Wed, 26 Nov 2025 21:43:28 +0000 (10:43 +1300)
commit42473b3b31238b15cc3c030b4416b2ee79508d8c
tree41e1c0dd763abfaa6db3cf9fc1fe7d738dd8164b
parentdbdc717ac6743074c3a55fc5c380638c91d24afd
Have the planner replace COUNT(ANY) with COUNT(*), when possible

This adds SupportRequestSimplifyAggref to allow pg_proc.prosupport
functions to receive an Aggref and allow them to determine if there is a
way that the Aggref call can be optimized.

Also added is a support function to allow transformation of COUNT(ANY)
into COUNT(*).  This is possible to do when the given "ANY" cannot be
NULL and also that there are no ORDER BY / DISTINCT clauses within the
Aggref.  This is a useful transformation to do as it is common that
people write COUNT(1), which until now has added unneeded overhead.
When counting a NOT NULL column.  The overheads can be worse as that
might mean deforming more of the tuple, which for large fact tables may
be many columns in.

It may be possible to add prosupport functions for other aggregates.  We
could consider if ORDER BY could be dropped for some calls, e.g. the
ORDER BY is quite useless in MAX(c ORDER BY c).

There is a little bit of passing fallout from adjusting
expr_is_nonnullable() to handle Const which results in a plan change in
the aggregates.out regression test.  Previously, nothing was able to
determine that "One-Time Filter: (100 IS NOT NULL)" was always true,
therefore useless to include in the plan.

Author: David Rowley <dgrowleyml@gmail.com>
Reviewed-by: Corey Huinker <corey.huinker@gmail.com>
Reviewed-by: Matheus Alcantara <matheusssilv97@gmail.com>
Discussion: https://postgr.es/m/CAApHDvqGcPTagXpKfH=CrmHBqALpziThJEDs_MrPqjKVeDF9wA@mail.gmail.com
contrib/postgres_fdw/expected/postgres_fdw.out
src/backend/optimizer/plan/initsplan.c
src/backend/optimizer/util/clauses.c
src/backend/utils/adt/int8.c
src/include/nodes/supportnodes.h
src/include/optimizer/optimizer.h
src/test/regress/expected/aggregates.out
src/test/regress/sql/aggregates.sql
src/tools/pgindent/typedefs.list