Fix UNION planner estimate_num_groups with varno==0
authorDavid Rowley <[email protected]>
Thu, 6 Nov 2025 03:34:55 +0000 (16:34 +1300)
committerDavid Rowley <[email protected]>
Thu, 6 Nov 2025 03:34:55 +0000 (16:34 +1300)
commiteaa159632d034a59ede1695f4b86098b1a372b48
tree3302fde0872fb7cf0805fa6aa99ccd264fc9df65
parenta3ebec4e4cf6625a2bab4db2830d57d25a34ba1f
Fix UNION planner estimate_num_groups with varno==0

03d40e4b5 added code to provide better row estimates for when a UNION
query ended up only with a single child due to other children being
found to be dummy rels.  In that case, ordinarily it would be ok to call
estimate_num_groups() on the targetlist of the only child path, however
that's not safe to do if the UNION child is the result of some other set
operation as we generate targetlists containing Vars with varno==0 for
those, which estimate_num_groups() can't handle.  This could lead to:

ERROR:  XX000: no relation entry for relid 0

Fix this by avoiding doing this when the only child is the result of
another set operation.  In that case we'll fall back on the
assume-all-rows-are-unique method.

Reported-by: Alexander Lakhin <[email protected]>
Author: David Rowley <[email protected]>
Discussion: https://postgr.es/m/cfbc99e5-9d44-4806-ba3c-f36b57a85e21@gmail.com
src/backend/optimizer/prep/prepunion.c
src/test/regress/expected/union.out
src/test/regress/sql/union.sql