Re: Teaching planner to short-circuit empty UNION/EXCEPT/INTERSECT inputs

David Rowley <dgrowleyml@gmail.com>

From: David Rowley <dgrowleyml@gmail.com>
To: Tom Lane <tgl@sss.pgh.pa.us>
Cc: PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>
Date: 2025-10-07T01:19:05Z
Lists: pgsql-hackers
On Sun, 5 Oct 2025 at 13:56, David Rowley <dgrowleyml@gmail.com> wrote:
> Another alternative that I'm thinking about which might be better is
> to double-down on the varno==0 and invent a special varno and define
> SETOP_VAR. I'd feel better about doing that as I didn't feel good
> about coding the magic number for the if(var->varno == 0) check in
> set_plan_refs() to make the T_Result work in EXPLAIN VERBOSE.

I decided not to do it that way and instead just added code to create
a varno==1 Var in setrefs.c.  This basically amounts to following on
with the varno==0 hack used in prepunion.c.

The reason I didn't go down the route of SETOP_VAR was that it's still
a hack, it's just making it look a bit more official.  I suppose the
correct way to fix all this and get rid of the varno==0 stuff forever
is to have a proper top-level RTE for the top-level set operation and
make it so each child is an OTHER_MEMBER rel at that query level. It
felt like going a bit too far to do something like that to fix this
bug, so I didn't explore that further.

David



Commits

  1. Fix UNION planner estimate_num_groups with varno==0

  2. Fix possible usage of incorrect UPPERREL_SETOP RelOptInfo

  3. Teach planner to short-circuit EXCEPT/INTERSECT with dummy inputs

  4. Fix incorrect targetlist in dummy UNIONs

  5. Teach UNION planner to remove dummy inputs