Re: [PROPOSAL] Expand OR clauses in joins to UNION ALL paths

From: Ayoub Kazar <ayoub(dot)kazar(at)data-bene(dot)io>
To: Robert Haas <robertmhaas(at)gmail(dot)com>
Cc: Zsolt Parragi <zsolt(dot)parragi(at)percona(dot)com>, pgsql-hackers(at)lists(dot)postgresql(dot)org
Subject: Re: [PROPOSAL] Expand OR clauses in joins to UNION ALL paths
Date: 2026-11-23 15:47:06
Message-ID: 69640c32-f4b7-4c46-b573-62f0ca72d7df@data-bene.io
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

Hi,

On 06/11/2026 17:28, Robert Haas wrote:
> Well, I think that you've submitted multiple versions of this patch
> now that failed tests or had easy-to-find defects. I suggest putting
> considerably more effort into this patch before posting each new
> version. That should certainly include making the tests pass, but also
> deeper thinking about what the patch is doing and how it's doing it,
> and LLM-driven review as well.
>
> With respect to pg_plan_advice specifically, I tried to design the
> module in a way where most planner features wouldn't need to make
> updates to it, but planner changes that create entirely new plan
> shapes likely will have to extend pg_plan_advice as well. Or, at the
> very least, find some way to exclude whatever they do from its scope,
> so that test_plan_advice doesn't visibly break. One wrinkle in this
> particular case is that set operation planning isn't currently covered
> by pg_plan_advice, because we have no hooks with which to enforce
> advice in such locations. That would be good to fix, regardless of
> this patch. Another wrinkle is that this patch uses set operation
> constructs in places where the current planner doesn't, which will
> complicate pg_plan_advice's attempts to understand the resulting plan.
So i understood that there's no need do all that set operations work,
all we need is to bound each of the potential Append subpaths (children)
with a subquery (provided that we align targetlists to whatever was
planned for that join path).
I think i'm actually grateful for pg_plan_advice not
allowing/understanding the previous approach, that would've been messier
than i thought in the beginning.
Also previously, an Append would be on top of join relations only in the
case of partitionwise joins, with OR Expansion that wouldn't be the case
anymore, this is taught to createplan.c in v7.
>
> That might not be the first thing to worry about here. Making sure
> that everything works correctly in all the straightforward cases is
> probably priority 1, and using something like sqlsmith to aid testing
> will probably help.
Oh yeah, totally agree, this was done for v7, hoping it was enough...
>
> From an design point of view, explosions in memory consumption and
> planning time are worth a lot of careful thought. It's probably not
> that difficult to just impose some kind of arbitrary cutoff, but that
> tends not to be a very nice solution. For example, if you say, well,
> we'll only consider this optimization when the number of "OR" arms is
> 4 or less, then somebody might see an abrupt plan quality regression
> when they go from 4 "OR" arms to 5.
>
Okay so this is a very complicated one, so lets restate the ideas for
clarity...

First, consider the per-candidate (clause) approach taken in v7 (what
Tom also did before). Here, each top-level OR clause in the
WHERE clause is evaluated independently as an expansion candidate. If a
candidate clause has N arms (with N <= or_expansion_limit), we plan N arms.
However if a query contains multiple conjoined OR clauses, such as
WHERE (A1 OR B1) AND (A2 OR B2), expanding one candidate clause leaves the
remaining OR clause unexpanded inside each branch as part of the join
filter.
Because the unexpanded part still suffers from the exact same planning
issues as the original query. But it can be still faster than the
unexpanded on many occasions, so its not completely unwelcomed.
> It's worth asking whether there's
> some way to degrade gracefully rather than having a sharp edge.
For that case, we can make this an effort based limit, like
join_collapse_limit? i.e expand arms up until that limit, the rest is
left out as the last branch not expanded, this is fine in general and i
think is better.

Other approaches i find worth considering:
- Full expansion:
In the previous approach, having many ANDs of OR clauses (CNF:
Conjunctive normal form) doesn't let us expand everything at the same
time, so this takes us to transforming whatever input we have into a DNF
(Disjunctive normal form) just for OR Expansion, the idea of reducing
WHERE clause to DNF or CNF was removed in 9888192fb77. Now for the
purposes of OR Expansion having a DNF makes more sense than for the
general case (because you actually give opportunity for every single
disjunct to benefit from an index, a better join, ..etc), though this
comes with some issues:

1- The number of disjuncts can easily explode, e.g: (A OR B) AND (C OR
D) <=> (A AND C) OR (A AND D) OR (B AND C) OR (B AND D), in general the
number is the product of the number of literals in each clause.
- We can limit this by a GUC, again with the same idea, expand up to
that limit, and leave the rest (in whatever form we want at this point)
in its separate branch.
- Also an interesting idea is to have a hardcoded limit that says if we
think that the DNF would have more than the limit (e.g 20, and remove
the GUC if we do this), don't consider doing this full expansion at all,
do the per candidate/clause expansion instead.
2- It can remove the opportunity for SAOP optimization inside a single
OR clause, i'll discuss this in details later below.

For completeness, i saw PolarDB for PostgreSQL (a fork) has a cost
threshold guc for OR-expansion, only considering expansion if the
estimated cost of the not expanded
query exceeds a high GUC value (e.g. cost > 50,000). I'm not a fan of
this tbh, unless someone would like to have this control instead,
curious to see what you think.

>
> Zsolt's point about what you've excluded from the patch is also worth
> a lot of thought. A patch that excludes cases unnecessarily because
> they seemed hard is unlikely to be accepted. On the other hand, a
> patch that tries too hard to accept cases that aren't a natural fit
> for what the patch does is also unlikely to be accepted. You want to
> hit the sweet spot in the middle, where you're supporting the things
> that you reasonably can, and punting the things you can't reasonably
> support with clear explanations as to why not.
Indeed, the cases left unsupported in v7 are as you said to be unnatural
or just unsafe:
- Volatile functions are just unsafe to duplicate across branches, CTEs
would probably expensive duplicate work and also violate single
evaluation (unless its materialized or made it share work between arms,
seems like an improvement for later).
- Correlated subqueries that stay as subplans also would duplicate
expensive work and require recursively checking for volatile functions
and so on, is this even worth consider working on?
- FULL OUTER joins also are unsafe, reduce_outer_joins() simplifies a
FULL join
into a LEFT or INNER join in some arms but not others, producing asymmetric
join reduction across arms.
- Expansion is restricted to the top-level query (root->parent_root ==
NULL) to prevent exponential planning recursion.

Note: After switching to the idea of subquery boundary on Append
children, partitioned tables become safe, so now pruning works as
expected (unless someone can break this in a way i couldn't ...).

Things worth mentioning:
- SAOP
In many queries OR expansion and SAOP can compete against each other,
the simplest example is a test in join.sql:
SELECT COUNT(*) FROM tenk1 t1, tenk1 t2
WHERE t2.thousand = t1.tenthous OR t2.thousand = t1.unique1 OR
t2.thousand = t1.unique2;
It seems okay to let it be the case, but this changes the expected test
result, i've disabled or expansion for this case, the test is intended
for SAOP so i thought i can't just let or expansion change its result!
what should i do here?

- Sorts and MergeAppends
Would it be wise to consider allowing sorting to go do to join relations
so that we can benefit from a MergeAppend? this would be VERY good for
TOP N queries (some Append arms can just never run if topn is satisfied
from above branches) and just ORDER BY queries. It can much better than
a top level Sort above the Append.
It didn't seem too complicated to support this by correctly passing
pathkeys down. I can either do this in the same patch or as 0002, if it
makes sense.

- Parallel queries
v7 already emits parallel queries in the different possible shapes,
thanks to add_paths_to_append_rel we just reuse the existing infra for
different append paths generation.

- Dead RTEs in rtable when OR Expansion doesn't win
I still can't decide on this, there are many places where RTEs are left
and guaranteed to never be touched, AFAIK its also safe to do in this
case, is there any opposition against it?
> There's an old adage that the first 90% of the project accounts for
> 90% of the work, and the last 10% of the project accounts for the
> other 90% of the work. In other words, people tend to underestimate
> what percentage of the necessary effort they've already invested. It's
> easy to feel good when things start working, and to underestimate how
> much polishing remains before you have something that can actually be
> shipped. Reading the thread and not the patch, my estimate of what
> part of the required work you've done is around 1%. I'm not saying
> that to be mean: I'm trying to help you understand what the magnitude
> of this project is likely to be, so you can make an informed decision
> about how to proceed. I'd love to have this feature, but it's not
> going to be easy to get from here to there.
Thanks for the advice Robert, very helpful and much appreciated.

Attached is v7. I recommend reading the header comment of planorexpand
for a nicer high level overview on whats going on.

Regards,
Ayoub Kazar

Attachment Content-Type Size
v7-0001-Expand-OR-clauses-in-joins-to-UNION-ALL-Append-paths.patch text/x-patch 74.1 KB

In response to

Browse pgsql-hackers by date

  From Date Subject
Previous Message Peter Geoghegan 2026-11-23 15:38:45 Re: Showing "Table Block Fetches" in EXPLAIN ANALYZE for index-only scans