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
From 30215a507a1e6cb191459560202156c860789ee5 Mon Sep 17 00:00:00 2001
From: AyoubKAZ <[email protected]>
Date: Mon, 23 Nov 2026 15:48:47 +0100
Subject: [PATCH v7] Expand OR clauses in joins to UNION ALL (Append) paths
When a query contains top-level multi-relation OR clauses, such as
WHERE (a.x = 1 AND b.y = 1) OR (a.x = 2 AND b.y = 2), the planner
traditionally forms a single join tree with the disjunction evaluated
as a join filter. This prevents pushing branch restrictions down into
single-relation index scans, pruning unneeded partitions, or choosing
join algorithms and order better specialized to each branch.
This commit introduces OR-clause expansion as an alternative physical
path. Eligible top-level OR clauses are expanded into UNION ALL (Append)
paths. Each disjunctive branch is planned as an independent subquery
arm via query_planner(), allowing relation-level index scans and joins
specialized to that branch. Duplicate rows are avoided without an
explicit deduplication step by adding null-safe exclusion conditions
(AND ((earlier_branch) IS NOT TRUE)) to subsequent branches.
Each arm's cheapest paths are wrapped in synthetic SubqueryScan paths
to align targetlists with the master joinrel, and competing Append and
Parallel Append paths are generated through add_paths_to_append_rel().
Controlled by the new GUC or_expansion_limit (default 8; 0 disables).
---
src/backend/optimizer/plan/Makefile | 1 +
src/backend/optimizer/plan/createplan.c | 12 +-
src/backend/optimizer/plan/meson.build | 1 +
src/backend/optimizer/plan/planner.c | 16 +
src/backend/optimizer/plan/planorexpand.c | 891 ++++++++++++++++++
src/backend/utils/misc/guc_parameters.dat | 10 +
src/backend/utils/misc/postgresql.conf.sample | 1 +
src/include/optimizer/planmain.h | 8 +
src/test/regress/expected/join.out | 2 +
src/test/regress/expected/or_expansion.out | 884 +++++++++++++++++
src/test/regress/parallel_schedule | 2 +-
src/test/regress/sql/join.sql | 4 +
src/test/regress/sql/or_expansion.sql | 326 +++++++
13 files changed, 2156 insertions(+), 2 deletions(-)
create mode 100644 src/backend/optimizer/plan/planorexpand.c
create mode 100644 src/test/regress/expected/or_expansion.out
create mode 100644 src/test/regress/sql/or_expansion.sql
diff --git a/src/backend/optimizer/plan/Makefile b/src/backend/optimizer/plan/Makefile
index 80ef162e484..3abff3baf65 100644
--- a/src/backend/optimizer/plan/Makefile
+++ b/src/backend/optimizer/plan/Makefile
@@ -18,6 +18,7 @@ OBJS = \
initsplan.o \
planagg.o \
planmain.o \
+ planorexpand.o \
planner.o \
setrefs.o \
subselect.o
diff --git a/src/backend/optimizer/plan/createplan.c b/src/backend/optimizer/plan/createplan.c
index bc991d31254..2d90e42f496 100644
--- a/src/backend/optimizer/plan/createplan.c
+++ b/src/backend/optimizer/plan/createplan.c
@@ -1274,7 +1274,17 @@ create_append_plan(PlannerInfo *root, AppendPath *best_path, int flags)
plan->plan.qual = NIL;
plan->plan.lefttree = NULL;
plan->plan.righttree = NULL;
- plan->apprelids = rel->relids;
+
+ /*
+ * An Append on an unpartitioned join rel (such as an OR-clause expansion
+ * into UNION ALL) does not form an appendrel and has no partition
+ * pruning. Only partitioned tables or partitionwise joins have non-NULL
+ * apprelids.
+ */
+ if (IS_JOIN_REL(rel) && !IS_PARTITIONED_REL(rel))
+ plan->apprelids = NULL;
+ else
+ plan->apprelids = rel->relids;
plan->child_append_relid_sets = best_path->child_append_relid_sets;
if (pathkeys != NIL)
diff --git a/src/backend/optimizer/plan/meson.build b/src/backend/optimizer/plan/meson.build
index c565b2adbcc..7e900b3107b 100644
--- a/src/backend/optimizer/plan/meson.build
+++ b/src/backend/optimizer/plan/meson.build
@@ -6,6 +6,7 @@ backend_sources += files(
'initsplan.c',
'planagg.c',
'planmain.c',
+ 'planorexpand.c',
'planner.c',
'setrefs.c',
'subselect.c',
diff --git a/src/backend/optimizer/plan/planner.c b/src/backend/optimizer/plan/planner.c
index bd4062d4a8f..7ca001dbb00 100644
--- a/src/backend/optimizer/plan/planner.c
+++ b/src/backend/optimizer/plan/planner.c
@@ -1851,6 +1851,7 @@ grouping_planner(PlannerInfo *root, double tuple_fraction,
List *activeWindows = NIL;
grouping_sets_data *gset_data = NULL;
standard_qp_extra qp_extra;
+ List *or_cands;
/* A recursive query should always have setOperations */
Assert(!root->hasRecursion);
@@ -1953,6 +1954,13 @@ grouping_planner(PlannerInfo *root, double tuple_fraction,
*/
qp_extra.setop = setops;
+ /*
+ * Consider expanding eligible join OR clauses into UNION ALL (Append)
+ * paths. This needs to be close to query_planner(), because each arm
+ * clones root and runs query_planner() on its modified quals.
+ */
+ or_cands = plan_or_expansion_arms(root);
+
/*
* Generate the best unsorted and presorted paths for the scan/join
* portion of this Query, ie the processing represented by the
@@ -1962,6 +1970,14 @@ grouping_planner(PlannerInfo *root, double tuple_fraction,
*/
current_rel = query_planner(root, standard_qp_callback, &qp_extra);
+ /*
+ * If we generated any OR-expansion candidates, build Append paths and
+ * attach them to the topmost scan/join relation to compete against
+ * standard join paths.
+ */
+ if (or_cands != NIL)
+ add_or_expansion_paths(root, current_rel, or_cands);
+
/*
* Convert the query's result tlist into PathTarget format.
*
diff --git a/src/backend/optimizer/plan/planorexpand.c b/src/backend/optimizer/plan/planorexpand.c
new file mode 100644
index 00000000000..b01ce4ecdb3
--- /dev/null
+++ b/src/backend/optimizer/plan/planorexpand.c
@@ -0,0 +1,891 @@
+/*-------------------------------------------------------------------------
+ *
+ * planorexpand.c
+ * Consider whether join OR clauses can be expanded to UNION ALL
+ * (Append) paths.
+ *
+ * This module looks for top-level OR clauses whose arms reference multiple
+ * relations, and tries to generate paths representing conversion of such an
+ * OR clause into a UNION ALL operation. For example,
+ *
+ * SELECT ... FROM a, b WHERE (cond-on-A OR cond-on-B) AND other-conds
+ *
+ * can be implemented as
+ *
+ * SELECT ... FROM a, b WHERE cond-on-A AND other-conds
+ * UNION ALL
+ * SELECT ... FROM a, b WHERE cond-on-B AND other-conds
+ * AND ((cond-on-A) IS NOT TRUE)
+ *
+ * Ordinarily, PostgreSQL plans cross-relation disjunctions as a single join
+ * tree with the entire OR clause evaluated as a join filter. That prevents
+ * the planner from pushing branch-specific restrictions down into individual
+ * index scans, pruning unneeded partitions, or choosing join orders tailored
+ * to each branch. By expanding each branch into an independent query ("arm"),
+ * each arm can be planned with restriction clauses specific to that arm,
+ * often allowing fast index scans, branch-specific partition pruning, or
+ * index-based joins that would otherwise be impossible.
+ *
+ * To avoid emitting duplicate rows without incurring the overhead of an
+ * expensive deduplication step, each branch after the first includes
+ * null-safe exclusion conditions:
+ *
+ * AND ((earlier-branch-condition) IS NOT TRUE)
+ *
+ * These exclusion clauses preserve the three-valued logic of the original OR:
+ * a subsequent branch excludes only those rows that were already produced by
+ * an earlier branch, while correctly retaining rows where earlier conditions
+ * evaluated to NULL or false. Consequently, the arm paths can be combined
+ * directly with an Append node without any top-level sort or hashing.
+ *
+ * Expansion is considered in grouping_planner() just before standard
+ * scan/join planning. For each suitable candidate OR clause, each arm is
+ * planned in an independent PlannerInfo subroot using query_planner(),
+ * allowing ordinary path-generation machinery to explore the optimal access
+ * methods for that arm. Each arm is then represented by a synthetic
+ * RTE_SUBQUERY entry in the master query's rangetable, providing a clean
+ * abstraction boundary. The resulting arm paths are aligned with the master
+ * targetlist and combined into an AppendPath (or Parallel AppendPath), which
+ * is attached to the top-level scan/join relation to compete on cost against
+ * conventional join paths.
+ *
+ * We must insist that WHERE and JOIN/ON clauses contain no volatile functions
+ * or correlated subplans, because branch conditions are evaluated multiple
+ * times across arms and exclusion tests. We also disallow FULL joins, because
+ * branch restrictions can cause reduce_outer_joins() to simplify a FULL join
+ * into an inner or left join in some arms but not others, producing asymmetric
+ * join reduction. Active unflattened subqueries and CTEs are likewise rejected
+ * because evaluating them independently in each arm would violate
+ * single-evaluation semantics or multiply expensive work.
+ *
+ * Because planning each arm requires an independent invocation of
+ * query_planner(), planning overhead scales with the number of arms. The
+ * or_expansion_limit GUC caps this overhead by setting the maximum number of
+ * arms an OR clause may contain to be considered for expansion. If a candidate
+ * clause contains more arms than this threshold, it is left unexpanded.
+ * Setting or_expansion_limit to zero (or less than two) basically just disables the feature
+ * entirely.
+ *
+ *
+ * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ *
+ * IDENTIFICATION
+ * src/backend/optimizer/plan/planorexpand.c
+ *
+ *-------------------------------------------------------------------------
+ */
+#include "postgres.h"
+
+#include "catalog/pg_class.h"
+#include "catalog/pg_type.h"
+#include "nodes/makefuncs.h"
+#include "nodes/nodeFuncs.h"
+#include "optimizer/clauses.h"
+#include "optimizer/cost.h"
+#include "optimizer/optimizer.h"
+#include "optimizer/pathnode.h"
+#include "optimizer/paths.h"
+#include "optimizer/planmain.h"
+#include "optimizer/planner.h"
+#include "optimizer/prep.h"
+#include "optimizer/subselect.h"
+#include "optimizer/tlist.h"
+#include "parser/parsetree.h"
+#include "port/pg_bitutils.h"
+
+/*
+ * or_expansion_limit sets the maximum number of arms in an OR clause that
+ * will be considered for expansion. Values below 2 disable expansion.
+ */
+int or_expansion_limit;
+
+typedef struct OrExpansionArm
+{
+ PlannerInfo *subroot;
+ RelOptInfo *final_rel;
+ Path *arm_path; /* Cheapest complete path */
+ Path *arm_partial_path; /* Cheapest partial path, if any */
+ Index arm_rti;
+} OrExpansionArm;
+
+typedef struct OrExpansionCandidate
+{
+ List *arms; /* List of OrExpansionArm */
+} OrExpansionCandidate;
+
+static bool is_query_safe_for_or_expansion(PlannerInfo *root);
+static void or_expansion_qp_callback(PlannerInfo *root, void *extra);
+static OrExpansionCandidate * create_or_expansion_subpaths(PlannerInfo *root,
+ BoolExpr *orclause,
+ int qual_idx);
+static bool has_outer_joins(Node *jtnode);
+static bool match_target_expr(Node *want, Node *have);
+static Path *or_expansion_align_path(PlannerInfo *root, RelOptInfo *joinrel,
+ Path *arm, PathTarget *target);
+static PathTarget *create_subquery_pathtarget(PlannerInfo *root, Index varno,
+ PathTarget *subtarget);
+static List *build_arm_subquery_colnames(int nattrs);
+
+/*
+ * is_query_safe_for_or_expansion
+ * Verify query-level safety gates for OR expansion.
+ */
+static bool
+is_query_safe_for_or_expansion(PlannerInfo *root)
+{
+ Query *parse = root->parse;
+ ListCell *lc;
+
+ /*
+ * Only top-level queries may be expanded. Expanding within subqueries
+ * risks planning overhead when nested.
+ */
+ if (root->parent_root != NULL)
+ return false;
+
+ /*
+ * Reject queries with volatile expressions in the jointree. Duplicating
+ * volatile functions across arms can alter execution counts or produce
+ * inconsistent results between arm evaluation and exclusion.
+ */
+ if (contain_volatile_functions((Node *) parse->jointree))
+ return false;
+
+ /*
+ * Reject queries whose jointree contains any SubPlan, AlternativeSubPlan,
+ * or SubLink. Uncorrelated sublinks were already converted to InitPlans
+ * represented by PARAM_EXEC Params, which are safely evaluated once at
+ * query startup and shared across arms. Correlated subplans cannot be
+ * duplicated across arms without outer-parameter coordination.
+ *
+ * SubPlans in the query targetlist need not be rejected here, because
+ * targetlist evaluation occurs above the Append during final projection.
+ */
+ if (contain_subplans((Node *) parse->jointree))
+ return false;
+
+ /*
+ * Check range table entries for features that are unsafe to replicate
+ * across multiple arms.
+ */
+ foreach(lc, parse->rtable)
+ {
+ RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
+
+ switch (rte->rtekind)
+ {
+ case RTE_RELATION:
+
+ /*
+ * Disallow TABLESAMPLE because arms planned independently
+ * would sample different random subsets of rows.
+ */
+ if (rte->tablesample != NULL)
+ return false;
+ break;
+
+ case RTE_JOIN:
+
+ /*
+ * Disallow queries with FULL joins. Addition of branch
+ * restriction clauses in individual arms can cause
+ * reduce_outer_joins() to simplify a FULL join into a LEFT or
+ * INNER join in some arms but not others, leading to
+ * asymmetric join reduction across arms.
+ */
+ if (rte->jointype == JOIN_FULL)
+ return false;
+ break;
+
+ case RTE_VALUES:
+ if (contain_volatile_functions((Node *) rte->values_lists) ||
+ contain_subplans((Node *) rte->values_lists))
+ return false;
+ break;
+
+ case RTE_FUNCTION:
+ if (contain_volatile_functions((Node *) rte->functions) ||
+ contain_subplans((Node *) rte->functions))
+ return false;
+ break;
+
+ case RTE_TABLEFUNC:
+ if (contain_volatile_functions((Node *) rte->tablefunc) ||
+ contain_subplans((Node *) rte->tablefunc))
+ return false;
+ break;
+
+ case RTE_SUBQUERY:
+
+ /*
+ * Allow flattened subqueries (subquery == NULL) and pulled-up
+ * UNION ALL append relations (rte->inh == true). Reject
+ * active unflattened subqueries because each arm would plan
+ * and execute an independent SubqueryScan, which could
+ * duplicate expensive work or introduce some inconsistencies.
+ */
+ if (rte->subquery != NULL && !rte->inh)
+ return false;
+ break;
+
+ case RTE_GROUP:
+ case RTE_RESULT:
+ break;
+
+ default:
+
+ /*
+ * Reject other RTE kinds, particularly CTEs, which cannot be
+ * duplicated across arms without sharing execution state.
+ */
+ return false;
+ }
+
+ /*
+ * Security barrier quals must not contain volatile functions or
+ * subplans.
+ */
+ if (contain_volatile_functions((Node *) rte->securityQuals) ||
+ contain_subplans((Node *) rte->securityQuals))
+ return false;
+ }
+
+ /*
+ * Append relations (such as pulled-up UNION ALL subqueries) can harbor
+ * expressions in their translation lists that will be substituted into
+ * arm quals during planning. Ensure that translated expressions contain
+ * no volatile functions or subplans, which would otherwise bypass the
+ * jointree checks above.
+ */
+ foreach(lc, root->append_rel_list)
+ {
+ AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(lc);
+
+ if (contain_volatile_functions((Node *) appinfo->translated_vars) ||
+ contain_subplans((Node *) appinfo->translated_vars))
+ return false;
+ }
+
+ return true;
+}
+
+/*
+ * has_outer_joins
+ * Recursively search the jointree for outer joins. Returns true if any
+ * JoinExpr satisfies IS_OUTER_JOIN (such as JOIN_LEFT or JOIN_ANTI).
+ */
+static bool
+has_outer_joins(Node *jtnode)
+{
+ if (jtnode == NULL)
+ return false;
+ if (IsA(jtnode, FromExpr))
+ {
+ FromExpr *f = (FromExpr *) jtnode;
+ ListCell *lc;
+
+ foreach(lc, f->fromlist)
+ {
+ if (has_outer_joins(lfirst(lc)))
+ return true;
+ }
+ return false;
+ }
+ if (IsA(jtnode, JoinExpr))
+ {
+ JoinExpr *j = (JoinExpr *) jtnode;
+
+ if (IS_OUTER_JOIN(j->jointype))
+ return true;
+ return has_outer_joins(j->larg) || has_outer_joins(j->rarg);
+ }
+
+ return false;
+}
+
+/*
+ * or_expansion_qp_callback
+ * Query planner callback for subroot arm planning.
+ */
+static void
+or_expansion_qp_callback(PlannerInfo *root, void *extra)
+{
+ /*
+ * We generate Append paths rather than MergeAppend paths, which do not
+ * preserve sort order across arms. MergeAppends are an improvement for
+ * the future.
+ */
+ root->group_pathkeys = NIL;
+ root->window_pathkeys = NIL;
+ root->distinct_pathkeys = NIL;
+ root->sort_pathkeys = NIL;
+ root->query_pathkeys = NIL;
+}
+
+/*
+ * create_or_expansion_subpaths
+ * Create best paths for each arm of the candidate OR clause and append
+ * synthetic RTE_SUBQUERY entries to root's rtable.
+ */
+static OrExpansionCandidate *
+create_or_expansion_subpaths(PlannerInfo *root, BoolExpr *orclause, int qual_idx)
+{
+ OrExpansionCandidate *cand;
+ List *arms = NIL;
+ int num_arms = list_length(orclause->args);
+ int k;
+
+ for (k = 0; k < num_arms; k++)
+ {
+ PlannerInfo *subroot;
+ Query *parse;
+ List *arm_quals = NIL;
+ Node *arm_k;
+ int j;
+ RelOptInfo *final_rel;
+ OrExpansionArm *arm;
+
+ /*
+ * Create a clean PlannerInfo for this arm, matching the subquery
+ * initialization pattern in subquery_planner() and
+ * pull_up_simple_subquery(). Using makeNode() ensures all workspace
+ * arrays, hash tables, and working lists are zeroed, avoiding fragile
+ * manual field resets.
+ */
+ subroot = makeNode(PlannerInfo);
+ subroot->parse = parse = (Query *) copyObject(root->parse);
+ subroot->glob = root->glob;
+ subroot->query_level = root->query_level + 1;
+ subroot->plan_name = choose_plan_name(root->glob, "orexpand", false);
+ subroot->alternative_plan_name = root->plan_name;
+ subroot->parent_root = root;
+ subroot->planner_cxt = CurrentMemoryContext;
+ subroot->processed_tlist = (List *) copyObject(root->processed_tlist);
+ subroot->append_rel_list = (List *) copyObject(root->append_rel_list);
+ subroot->qual_security_level = root->qual_security_level;
+ subroot->hasHavingQual = root->hasHavingQual;
+ subroot->hasLateralRTEs = root->hasLateralRTEs;
+ subroot->group_rtindex = root->group_rtindex;
+ subroot->numOrderedAggs = root->numOrderedAggs;
+ subroot->hasJoinRTEs = root->hasJoinRTEs;
+
+ /*
+ * If there is no ORDER BY, aggregation, grouping, or distinct, the
+ * Append directly feeds the Limit node, so inherit tuple_fraction and
+ * limit_tuples from grouping_planner. If not, those upper nodes will
+ * consume all tuples, so arms must optimize for total cost.
+ */
+ if (root->parse->sortClause == NIL &&
+ !root->parse->hasAggs &&
+ root->parse->groupClause == NIL &&
+ root->parse->havingQual == NULL &&
+ root->parse->distinctClause == NIL &&
+ root->parse->groupingSets == NIL &&
+ !root->parse->hasWindowFuncs &&
+ !root->parse->hasTargetSRFs)
+ {
+ subroot->tuple_fraction = root->tuple_fraction;
+ subroot->limit_tuples = root->limit_tuples;
+ }
+ else
+ {
+ subroot->tuple_fraction = 0.0;
+ subroot->limit_tuples = -1.0;
+ }
+
+ subroot->wt_param_id = -1;
+ subroot->join_domains = list_make1(makeNode(JoinDomain));
+
+ /*
+ * Build arm quals: R AND C_k AND (C_0 IS NOT TRUE) AND ... AND
+ * (C_{k-1} IS NOT TRUE)
+ */
+ arm_quals = list_delete_nth_cell(copyObject((List *) root->parse->jointree->quals),
+ qual_idx);
+
+ /* Add arm k's disjunct, flattened if it is an AND expression */
+ arm_k = (Node *) copyObject(list_nth(orclause->args, k));
+ arm_quals = list_concat(arm_quals, make_ands_implicit((Expr *) arm_k));
+
+ /* Add null-safe exclusion conditions for all previous arms */
+ for (j = 0; j < k; j++)
+ {
+ Node *prev_arm = (Node *) copyObject(list_nth(orclause->args, j));
+ BooleanTest *btest;
+
+ btest = makeNode(BooleanTest);
+ btest->arg = (Expr *) prev_arm;
+ btest->booltesttype = IS_NOT_TRUE;
+ btest->location = -1;
+
+ arm_quals = lappend(arm_quals, btest);
+ }
+
+ parse->jointree->quals = (Node *) arm_quals;
+
+ /* Re-run reduce_outer_joins if jointree contains outer joins */
+ if (has_outer_joins((Node *) parse->jointree))
+ {
+ reduce_outer_joins(subroot);
+
+ /*
+ * reduce_outer_joins() may update parse->targetList via
+ * remove_nulling_relids(). Re-sync processed_tlist so that
+ * varnullingrels are consistent during arm plan creation.
+ */
+ subroot->processed_tlist = (List *) copyObject(subroot->parse->targetList);
+ }
+
+ /* Plan this arm */
+ final_rel = query_planner(subroot, or_expansion_qp_callback, NULL);
+
+ if (!final_rel || !final_rel->cheapest_total_path ||
+ final_rel->cheapest_total_path->param_info != NULL)
+ return NULL;
+
+
+ /* Cope with params and initplans used within this subquery */
+ SS_identify_outer_params(subroot);
+ SS_charge_for_initplans(subroot, final_rel);
+
+ set_cheapest(final_rel);
+
+ arm = palloc_object(OrExpansionArm);
+ arm->subroot = subroot;
+ arm->final_rel = final_rel;
+ arm->arm_path = get_cheapest_fractional_path(final_rel,
+ subroot->tuple_fraction);
+ arm->arm_partial_path = (final_rel->partial_pathlist != NIL) ?
+ (Path *) linitial(final_rel->partial_pathlist) : NULL;
+ arm->arm_rti = 0;
+
+ arms = lappend(arms, arm);
+ }
+
+ cand = palloc_object(OrExpansionCandidate);
+ cand->arms = arms;
+ return cand;
+}
+
+/*
+ * plan_or_expansion_arms
+ * Check eligibility and generate subpaths for OR clauses in top-level WHERE.
+ * Called by grouping_planner() before query_planner().
+ */
+List *
+plan_or_expansion_arms(PlannerInfo *root)
+{
+ List *results = NIL;
+ Query *parse = root->parse;
+ bool checked_query = false;
+ ListCell *lc;
+ int qual_idx;
+
+ if (or_expansion_limit < 2)
+ return NIL;
+
+ if (parse->commandType != CMD_SELECT ||
+ parse->rowMarks != NIL ||
+ parse->setOperations != NULL ||
+ parse->cteList != NIL ||
+ root->hasRecursion)
+ return NIL;
+
+ if (list_length(parse->rtable) < 2)
+ return NIL;
+
+ if (parse->jointree == NULL || parse->jointree->quals == NULL)
+ return NIL;
+
+ /* Scan top-level WHERE quals for eligible OR clauses */
+ qual_idx = 0;
+ foreach(lc, (List *) parse->jointree->quals)
+ {
+ Node *qual = (Node *) lfirst(lc);
+
+ if (is_orclause(qual))
+ {
+ BoolExpr *orclause = (BoolExpr *) qual;
+ int num_arms = list_length(orclause->args);
+ Relids all_arm_varnos;
+ int nrelations = 0;
+ int rti = -1;
+ OrExpansionCandidate *cand;
+
+ if (num_arms < 2 || num_arms > or_expansion_limit)
+ {
+ qual_idx++;
+ continue;
+ }
+
+ all_arm_varnos = pull_varnos(root, (Node *) orclause);
+
+ /*
+ * Require the OR clause to reference at least 2 distinct
+ * relations. pull_varnos() includes outer-join RTE_JOIN relids
+ * via Var.varnullingrels; skip these so we only count base
+ * relations.
+ */
+ while ((rti = bms_next_member(all_arm_varnos, rti)) >= 0)
+ {
+ RangeTblEntry *rte = rt_fetch(rti, parse->rtable);
+
+ if (rte->rtekind != RTE_JOIN)
+ nrelations++;
+ }
+ bms_free(all_arm_varnos);
+
+ if (nrelations < 2)
+ {
+ qual_idx++;
+ continue;
+ }
+
+ /* Query-level safety check */
+ if (!checked_query)
+ {
+ if (!is_query_safe_for_or_expansion(root))
+ return NIL;
+ checked_query = true;
+ }
+
+ /* Transform OR clause and generate subpaths for each arm */
+ cand = create_or_expansion_subpaths(root, orclause, qual_idx);
+ if (cand != NULL)
+ results = lappend(results, cand);
+ }
+ qual_idx++;
+ }
+
+ /*
+ * If any candidates were found, append their synthetic RTE_SUBQUERY
+ * entries to root's rtable in a single pass.
+ */
+ if (results != NIL)
+ {
+ ListCell *lc_cand;
+
+ foreach(lc_cand, results)
+ {
+ OrExpansionCandidate *cand = (OrExpansionCandidate *) lfirst(lc_cand);
+ ListCell *lc_arm;
+
+ foreach(lc_arm, cand->arms)
+ {
+ OrExpansionArm *arm = (OrExpansionArm *) lfirst(lc_arm);
+ RangeTblEntry *rte = makeNode(RangeTblEntry);
+
+ rte->rtekind = RTE_SUBQUERY;
+ rte->subquery = arm->subroot->parse;
+ rte->alias = NULL;
+ rte->eref = makeAlias(arm->subroot->plan_name, NIL);
+ rte->lateral = false;
+ rte->inh = false;
+ rte->inFromCl = false;
+
+ root->parse->rtable = lappend(root->parse->rtable, rte);
+ arm->arm_rti = list_length(root->parse->rtable);
+ }
+ }
+ }
+
+ return results;
+}
+
+/*
+ * match_target_expr
+ * Check if two targetlist expressions match, ignoring varnullingrels
+ * differences that may arise from outer join reduction in subroot.
+ */
+static bool
+match_target_expr(Node *want, Node *have)
+{
+ if (want == have)
+ return true;
+ if (want == NULL || have == NULL)
+ return false;
+ if (nodeTag(want) != nodeTag(have))
+ return false;
+
+ if (IsA(want, Var))
+ {
+ Var *v1 = (Var *) want;
+ Var *v2 = (Var *) have;
+
+ return (v1->varno == v2->varno &&
+ v1->varattno == v2->varattno &&
+ v1->varlevelsup == v2->varlevelsup);
+ }
+
+ if (IsA(want, PlaceHolderVar))
+ {
+ PlaceHolderVar *p1 = (PlaceHolderVar *) want;
+ PlaceHolderVar *p2 = (PlaceHolderVar *) have;
+
+ return (p1->phid == p2->phid &&
+ p1->phlevelsup == p2->phlevelsup);
+ }
+
+ return equal(want, have);
+}
+
+/*
+ * or_expansion_align_path
+ * Ensure the arm path emits columns in the exact order needed by target.
+ * If column order differs, wrap with a projection using the arm's own
+ * expressions.
+ */
+static Path *
+or_expansion_align_path(PlannerInfo *root, RelOptInfo *joinrel, Path *arm, PathTarget *target)
+{
+ List *want = target->exprs;
+ List *have = arm->pathtarget->exprs;
+ List *new_exprs = NIL;
+ ListCell *lc_want;
+ PathTarget *newtarget;
+
+ /* identical target lists */
+ if (equal(want, have))
+ return arm;
+
+ if (list_length(want) != list_length(have))
+ return NULL;
+
+ foreach(lc_want, want)
+ {
+ Node *want_node = (Node *) lfirst(lc_want);
+ Node *matched = NULL;
+ ListCell *lc;
+
+ foreach(lc, have)
+ {
+ Node *have_node = (Node *) lfirst(lc);
+
+ if (match_target_expr(want_node, have_node))
+ {
+ matched = have_node;
+ break;
+ }
+ }
+
+ if (matched == NULL)
+ return NULL;
+
+ new_exprs = lappend(new_exprs, matched);
+ }
+
+ if (equal(new_exprs, have))
+ return arm;
+
+ newtarget = create_empty_pathtarget();
+ newtarget->exprs = new_exprs;
+ set_pathtarget_cost_width(root, newtarget);
+
+ /* Apply projection in-place if we can, or wrap with a ProjectionPath */
+ return apply_projection_to_path(root, joinrel, arm, newtarget);
+}
+
+/*
+ * create_subquery_pathtarget
+ * Build a PathTarget for a synthetic subquery relation containing identity
+ * Vars referencing the subpath's output columns (varno, 1..n).
+ */
+static PathTarget *
+create_subquery_pathtarget(PlannerInfo *root, Index varno, PathTarget *subtarget)
+{
+ PathTarget *target = create_empty_pathtarget();
+ int attno = 0;
+ ListCell *lc;
+
+ foreach(lc, subtarget->exprs)
+ {
+ Node *expr = (Node *) lfirst(lc);
+ Var *var;
+
+ attno++;
+ var = makeVar(varno,
+ attno,
+ exprType(expr),
+ exprTypmod(expr),
+ exprCollation(expr),
+ 0);
+ target->exprs = lappend(target->exprs, var);
+ }
+
+ return set_pathtarget_cost_width(root, target);
+}
+
+/*
+ * build_arm_subquery_colnames
+ * Construct dummy column names for a synthetic subquery RTE.
+ *
+ * build_simple_rel() expects eref->colnames to have as many entries as
+ * the subquery emits in order to set max_attr and allocate attribute
+ * arrays. Because the synthetic SubqueryScan has a trivial targetlist
+ * and will be elided by setrefs.c, dummy column names suffice.
+ */
+static List *
+build_arm_subquery_colnames(int nattrs)
+{
+ List *colnames = NIL;
+ int i;
+
+ for (i = 0; i < nattrs; i++)
+ colnames = lappend(colnames, makeString(pstrdup("?column?")));
+
+ return colnames;
+}
+
+/*
+ * add_or_expansion_paths
+ * Combine arm subpaths into an AppendPath and add to the top join rel.
+ * Called by grouping_planner() right after query_planner().
+ */
+void
+add_or_expansion_paths(PlannerInfo *root, RelOptInfo *joinrel, List *or_cands)
+{
+ ListCell *lc;
+ bool added_any = false;
+ bool consider_parallel;
+
+ if (joinrel == NULL || joinrel->reltarget == NULL)
+ return;
+
+ consider_parallel = joinrel->consider_parallel &&
+ (max_parallel_workers_per_gather > 0);
+
+ foreach(lc, or_cands)
+ {
+ OrExpansionCandidate *cand = (OrExpansionCandidate *) lfirst(lc);
+ ListCell *lc_arm;
+ List *live_arm_rels = NIL;
+ bool cand_valid = true;
+
+ /*
+ * Build and populate synthetic relations for each arm.
+ */
+ foreach(lc_arm, cand->arms)
+ {
+ OrExpansionArm *arm = (OrExpansionArm *) lfirst(lc_arm);
+ Path *aligned_cheapest;
+ RelOptInfo *arm_rel;
+ SubqueryScanPath *sqpath;
+ RangeTblEntry *arm_rte;
+
+ /* Align the arm's cheapest path to determine the arm reltarget */
+ aligned_cheapest = or_expansion_align_path(arm->subroot,
+ arm->final_rel,
+ arm->arm_path,
+ joinrel->reltarget);
+ if (aligned_cheapest == NULL)
+ {
+ cand_valid = false;
+ break;
+ }
+
+ /* Synchronize subroot tlist with the arm's actual output target */
+ arm->subroot->processed_tlist =
+ arm->subroot->parse->targetList =
+ make_tlist_from_pathtarget(aligned_cheapest->pathtarget);
+
+ /*
+ * Provide column names for the synthetic subquery RTE so that
+ * build_simple_rel() accurately computes max_attr > 0.
+ */
+ arm_rte = rt_fetch(arm->arm_rti, root->parse->rtable);
+ arm_rte->eref->colnames =
+ build_arm_subquery_colnames(list_length(joinrel->reltarget->exprs));
+
+ /* Make rel for the synthetic subquery RTE */
+ arm_rel = build_simple_rel(root, arm->arm_rti, NULL);
+ arm_rel->subroot = arm->subroot;
+ arm_rel->tuples = arm_rel->rows = aligned_cheapest->rows;
+ arm_rel->consider_parallel = consider_parallel;
+ arm_rel->reltarget = create_subquery_pathtarget(root,
+ arm->arm_rti,
+ aligned_cheapest->pathtarget);
+
+ /* Cheapest total path */
+ sqpath = create_subqueryscan_path(root,
+ arm_rel,
+ aligned_cheapest,
+ true,
+ NIL,
+ NULL);
+ add_path(arm_rel, (Path *) sqpath);
+
+ /*
+ * If parallel execution is considered, populate partial and
+ * parallel-safe paths on arm_rel so that
+ * add_paths_to_append_rel() can generate parallel Append paths.
+ */
+ if (consider_parallel)
+ {
+ if (arm->arm_partial_path != NULL)
+ {
+ Path *aligned_partial;
+ Path *ps_partial;
+
+ aligned_partial = or_expansion_align_path(arm->subroot,
+ arm->final_rel,
+ arm->arm_partial_path,
+ joinrel->reltarget);
+ ps_partial = (Path *) create_subqueryscan_path(root,
+ arm_rel,
+ aligned_partial,
+ true,
+ NIL,
+ NULL);
+ add_partial_path(arm_rel, ps_partial);
+ }
+
+ /*
+ * If the cheapest path is not parallel-safe, try a
+ * parallel-safe inner path.
+ */
+ if (!aligned_cheapest->parallel_safe)
+ {
+ Path *nppath;
+
+ nppath = get_cheapest_parallel_safe_total_inner(arm->final_rel->pathlist);
+ if (nppath != NULL)
+ {
+ Path *aligned_np;
+ Path *ps_np;
+
+ aligned_np = or_expansion_align_path(arm->subroot,
+ arm->final_rel,
+ nppath,
+ joinrel->reltarget);
+ ps_np = (Path *) create_subqueryscan_path(root,
+ arm_rel,
+ aligned_np,
+ true,
+ NIL,
+ NULL);
+ add_path(arm_rel, ps_np);
+ }
+ }
+ }
+
+ set_cheapest(arm_rel);
+ live_arm_rels = lappend(live_arm_rels, arm_rel);
+ }
+
+ /*
+ * If all arms produced valid subpaths, generate AppendPath and
+ * Parallel AppendPath alternatives via add_paths_to_append_rel().
+ */
+ if (cand_valid)
+ {
+ add_paths_to_append_rel(root, joinrel, live_arm_rels);
+ added_any = true;
+ }
+ }
+
+ /* Refigure which is the cheapest path for the joinrel */
+ if (added_any)
+ set_cheapest(joinrel);
+}
diff --git a/src/backend/utils/misc/guc_parameters.dat b/src/backend/utils/misc/guc_parameters.dat
index 8a8f1cca097..542cb1a7b75 100644
--- a/src/backend/utils/misc/guc_parameters.dat
+++ b/src/backend/utils/misc/guc_parameters.dat
@@ -2335,6 +2335,16 @@
ifdef => 'DEBUG_BOUNDED_SORT',
},
+{ name => 'or_expansion_limit', type => 'int', context => 'PGC_USERSET', group => 'QUERY_TUNING_OTHER',
+ short_desc => 'Sets the maximum number of OR arms considered for OR-expansion.',
+ long_desc => 'The planner will consider expanding OR clauses if they have no more than this many arms. 0 disables OR-expansion.',
+ flags => 'GUC_EXPLAIN',
+ variable => 'or_expansion_limit',
+ boot_val => '8',
+ min => '0',
+ max => 'INT_MAX',
+},
+
{ name => 'output_plugin_libraries', type => 'string', context => 'PGC_SUSET', group => 'REPLICATION_SENDING',
short_desc => 'Lists libraries that may be named as logical decoding output plugins.',
long_desc => 'Users with REPLICATION privileges may only use plugins in this list when creating logical replication slots.',
diff --git a/src/backend/utils/misc/postgresql.conf.sample b/src/backend/utils/misc/postgresql.conf.sample
index b492b3af06c..c055a4473b0 100644
--- a/src/backend/utils/misc/postgresql.conf.sample
+++ b/src/backend/utils/misc/postgresql.conf.sample
@@ -496,6 +496,7 @@
#jit = off # allow JIT compilation
#join_collapse_limit = 8 # 1 disables collapsing of explicit
# JOIN clauses
+#or_expansion_limit = 8 # 0 disables OR-expansion to UNION ALL
#plan_cache_mode = auto # auto, force_generic_plan or
# force_custom_plan
#recursive_worktable_factor = 10.0 # range 0.001-1000000
diff --git a/src/include/optimizer/planmain.h b/src/include/optimizer/planmain.h
index c23ab568b98..d338b7705ba 100644
--- a/src/include/optimizer/planmain.h
+++ b/src/include/optimizer/planmain.h
@@ -36,6 +36,14 @@ extern RelOptInfo *query_planner(PlannerInfo *root,
*/
extern void preprocess_minmax_aggregates(PlannerInfo *root);
+/*
+ * prototypes for plan/planorexpand.c
+ */
+extern PGDLLIMPORT int or_expansion_limit;
+extern List *plan_or_expansion_arms(PlannerInfo *root);
+extern void add_or_expansion_paths(PlannerInfo *root, RelOptInfo *joinrel,
+ List *or_cands);
+
/*
* prototypes for plan/createplan.c
*/
diff --git a/src/test/regress/expected/join.out b/src/test/regress/expected/join.out
index 440511d21b5..1a17abc911d 100644
--- a/src/test/regress/expected/join.out
+++ b/src/test/regress/expected/join.out
@@ -13353,6 +13353,7 @@ WHERE ss.unique1 = ss.phv AND t1.unique1 < 100;
-- Test for a nested loop join involving index scan, transforming OR-clauses
-- to SAOP.
--
+SET or_expansion_limit = 0;
EXPLAIN (COSTS OFF)
SELECT COUNT(*) FROM tenk1 t1, tenk1 t2
WHERE t2.thousand = t1.tenthous OR t2.thousand = t1.unique1 OR t2.thousand = t1.unique2;
@@ -13372,6 +13373,7 @@ WHERE t2.thousand = t1.tenthous OR t2.thousand = t1.unique1 OR t2.thousand = t1.
20000
(1 row)
+RESET or_expansion_limit;
EXPLAIN (COSTS OFF)
SELECT COUNT(*) FROM onek t1 LEFT JOIN tenk1 t2
ON (t2.thousand = t1.tenthous OR t2.thousand = t1.thousand);
diff --git a/src/test/regress/expected/or_expansion.out b/src/test/regress/expected/or_expansion.out
new file mode 100644
index 00000000000..a46934232f5
--- /dev/null
+++ b/src/test/regress/expected/or_expansion.out
@@ -0,0 +1,884 @@
+--
+-- Tests for OR-clause expansion into UNION ALL Append paths
+--
+-- Initial GUC check
+SHOW or_expansion_limit;
+ or_expansion_limit
+--------------------
+ 8
+(1 row)
+
+CREATE TABLE orexp_a (id int, val int);
+CREATE TABLE orexp_b (x int, y int, val int);
+INSERT INTO orexp_a VALUES
+ (1, 10),
+ (2, 20),
+ (3, 30),
+ (4, NULL),
+ (5, 50);
+INSERT INTO orexp_b VALUES
+ (1, 99, 100),
+ (99, 2, 200),
+ (3, 3, 300),
+ (4, 99, 400),
+ (99, 99, 500),
+ (NULL, NULL, 600);
+--
+-- Basic OR-clause expansion
+--
+-- Disjunction on join keys across two tables
+EXPLAIN (COSTS OFF)
+SELECT a.id, b.x, b.y FROM orexp_a a, orexp_b b
+WHERE a.id = b.x OR a.id = b.y
+ORDER BY a.id, b.x, b.y;
+ QUERY PLAN
+-----------------------------------------------------------
+ Sort
+ Sort Key: a.id, b.x, b.y
+ -> Append
+ -> Merge Join
+ Merge Cond: (b.x = a.id)
+ -> Sort
+ Sort Key: b.x
+ -> Seq Scan on orexp_b b
+ -> Sort
+ Sort Key: a.id
+ -> Seq Scan on orexp_a a
+ -> Merge Join
+ Merge Cond: (b_1.y = a_1.id)
+ Join Filter: ((a_1.id = b_1.x) IS NOT TRUE)
+ -> Sort
+ Sort Key: b_1.y
+ -> Seq Scan on orexp_b b_1
+ -> Sort
+ Sort Key: a_1.id
+ -> Seq Scan on orexp_a a_1
+(20 rows)
+
+SELECT a.id, b.x, b.y FROM orexp_a a, orexp_b b
+WHERE a.id = b.x OR a.id = b.y
+ORDER BY a.id, b.x, b.y;
+ id | x | y
+----+----+----
+ 1 | 1 | 99
+ 2 | 99 | 2
+ 3 | 3 | 3
+ 4 | 4 | 99
+(4 rows)
+
+-- Compare with expansion disabled to confirm semantic equivalence
+SET or_expansion_limit = 0;
+EXPLAIN (COSTS OFF)
+SELECT a.id, b.x, b.y FROM orexp_a a, orexp_b b
+WHERE a.id = b.x OR a.id = b.y
+ORDER BY a.id, b.x, b.y;
+ QUERY PLAN
+-----------------------------------------------------
+ Sort
+ Sort Key: a.id, b.x, b.y
+ -> Nested Loop
+ Join Filter: ((a.id = b.x) OR (a.id = b.y))
+ -> Seq Scan on orexp_a a
+ -> Materialize
+ -> Seq Scan on orexp_b b
+(7 rows)
+
+SELECT a.id, b.x, b.y FROM orexp_a a, orexp_b b
+WHERE a.id = b.x OR a.id = b.y
+ORDER BY a.id, b.x, b.y;
+ id | x | y
+----+----+----
+ 1 | 1 | 99
+ 2 | 99 | 2
+ 3 | 3 | 3
+ 4 | 4 | 99
+(4 rows)
+
+RESET or_expansion_limit;
+--
+-- Three-valued logic and duplicate elimination
+--
+-- Row (3, 30) from orexp_a and (3, 3, 300) from orexp_b satisfies both arms:
+-- a.id = b.x (3 = 3) AND a.id = b.y (3 = 3).
+-- The (a.id = b.x) IS NOT TRUE exclusion condition in the second arm ensures
+-- it is emitted exactly once. Rows with NULLs are correctly handled.
+EXPLAIN (COSTS OFF)
+SELECT a.id, a.val, b.x, b.y, b.val
+FROM orexp_a a, orexp_b b
+WHERE (a.id = b.x OR a.id = b.y) AND (a.val IS NOT NULL OR b.val > 200)
+ORDER BY a.id, b.x, b.y;
+ QUERY PLAN
+------------------------------------------------------------------------------------------------------------
+ Sort
+ Sort Key: a.id, b.x, b.y
+ -> Append
+ -> Merge Join
+ Merge Cond: (b.x = a.id)
+ Join Filter: ((a.val IS NOT NULL) OR (b.val > 200))
+ -> Sort
+ Sort Key: b.x
+ -> Seq Scan on orexp_b b
+ -> Sort
+ Sort Key: a.id
+ -> Seq Scan on orexp_a a
+ -> Merge Join
+ Merge Cond: (b_1.y = a_1.id)
+ Join Filter: (((a_1.val IS NOT NULL) OR (b_1.val > 200)) AND ((a_1.id = b_1.x) IS NOT TRUE))
+ -> Sort
+ Sort Key: b_1.y
+ -> Seq Scan on orexp_b b_1
+ -> Sort
+ Sort Key: a_1.id
+ -> Seq Scan on orexp_a a_1
+(21 rows)
+
+SELECT a.id, a.val, b.x, b.y, b.val
+FROM orexp_a a, orexp_b b
+WHERE (a.id = b.x OR a.id = b.y) AND (a.val IS NOT NULL OR b.val > 200)
+ORDER BY a.id, b.x, b.y;
+ id | val | x | y | val
+----+-----+----+----+-----
+ 1 | 10 | 1 | 99 | 100
+ 2 | 20 | 99 | 2 | 200
+ 3 | 30 | 3 | 3 | 300
+ 4 | | 4 | 99 | 400
+(4 rows)
+
+--
+-- Multi-arm expansion (3 arms)
+--
+-- Arm 2 excludes Arm 0; Arm 3 excludes both Arm 0 and Arm 1.
+EXPLAIN (COSTS OFF)
+SELECT a.id, b.x, b.y, b.val FROM orexp_a a, orexp_b b
+WHERE a.id = b.x OR a.id = b.y OR a.val = b.val
+ORDER BY a.id, b.x, b.y, b.val;
+ QUERY PLAN
+------------------------------------------------------------------------------------------------
+ Sort
+ Sort Key: a.id, b.x, b.y, b.val
+ -> Append
+ -> Merge Join
+ Merge Cond: (b.x = a.id)
+ -> Sort
+ Sort Key: b.x
+ -> Seq Scan on orexp_b b
+ -> Sort
+ Sort Key: a.id
+ -> Seq Scan on orexp_a a
+ -> Merge Join
+ Merge Cond: (b_1.y = a_1.id)
+ Join Filter: ((a_1.id = b_1.x) IS NOT TRUE)
+ -> Sort
+ Sort Key: b_1.y
+ -> Seq Scan on orexp_b b_1
+ -> Sort
+ Sort Key: a_1.id
+ -> Seq Scan on orexp_a a_1
+ -> Merge Join
+ Merge Cond: (b_2.val = a_2.val)
+ Join Filter: (((a_2.id = b_2.x) IS NOT TRUE) AND ((a_2.id = b_2.y) IS NOT TRUE))
+ -> Sort
+ Sort Key: b_2.val
+ -> Seq Scan on orexp_b b_2
+ -> Sort
+ Sort Key: a_2.val
+ -> Seq Scan on orexp_a a_2
+(29 rows)
+
+SELECT a.id, b.x, b.y, b.val FROM orexp_a a, orexp_b b
+WHERE a.id = b.x OR a.id = b.y OR a.val = b.val
+ORDER BY a.id, b.x, b.y, b.val;
+ id | x | y | val
+----+----+----+-----
+ 1 | 1 | 99 | 100
+ 2 | 99 | 2 | 200
+ 3 | 3 | 3 | 300
+ 4 | 4 | 99 | 400
+(4 rows)
+
+--
+-- Target list projection and expressions
+--
+-- Column order differs from scan order and includes cross-table expressions
+EXPLAIN (COSTS OFF)
+SELECT b.y, a.id + b.x AS sum_id_x, a.val, 'tag' AS literal
+FROM orexp_a a, orexp_b b
+WHERE a.id = b.x OR a.id = b.y
+ORDER BY sum_id_x, b.y;
+ QUERY PLAN
+-----------------------------------------------------------------
+ Sort
+ Sort Key: ((a.id + b.x)), b.y
+ -> Result
+ -> Append
+ -> Merge Join
+ Merge Cond: (b.x = a.id)
+ -> Sort
+ Sort Key: b.x
+ -> Seq Scan on orexp_b b
+ -> Sort
+ Sort Key: a.id
+ -> Seq Scan on orexp_a a
+ -> Merge Join
+ Merge Cond: (b_1.y = a_1.id)
+ Join Filter: ((a_1.id = b_1.x) IS NOT TRUE)
+ -> Sort
+ Sort Key: b_1.y
+ -> Seq Scan on orexp_b b_1
+ -> Sort
+ Sort Key: a_1.id
+ -> Seq Scan on orexp_a a_1
+(21 rows)
+
+SELECT b.y, a.id + b.x AS sum_id_x, a.val, 'tag' AS literal
+FROM orexp_a a, orexp_b b
+WHERE a.id = b.x OR a.id = b.y
+ORDER BY sum_id_x, b.y;
+ y | sum_id_x | val | literal
+----+----------+-----+---------
+ 99 | 2 | 10 | tag
+ 3 | 6 | 30 | tag
+ 99 | 8 | | tag
+ 2 | 101 | 20 | tag
+(4 rows)
+
+-- Whole-row references
+EXPLAIN (COSTS OFF)
+SELECT a.*, b.* FROM orexp_a a, orexp_b b
+WHERE a.id = b.x OR a.id = b.y
+ORDER BY a.id, b.x, b.y;
+ QUERY PLAN
+-----------------------------------------------------------
+ Sort
+ Sort Key: a.id, b.x, b.y
+ -> Append
+ -> Merge Join
+ Merge Cond: (b.x = a.id)
+ -> Sort
+ Sort Key: b.x
+ -> Seq Scan on orexp_b b
+ -> Sort
+ Sort Key: a.id
+ -> Seq Scan on orexp_a a
+ -> Merge Join
+ Merge Cond: (b_1.y = a_1.id)
+ Join Filter: ((a_1.id = b_1.x) IS NOT TRUE)
+ -> Sort
+ Sort Key: b_1.y
+ -> Seq Scan on orexp_b b_1
+ -> Sort
+ Sort Key: a_1.id
+ -> Seq Scan on orexp_a a_1
+(20 rows)
+
+--
+-- Upper planner nodes and cost propagation
+--
+-- Fast-start with LIMIT: tuple_fraction and limit_tuples passed to arms
+EXPLAIN (COSTS OFF)
+SELECT a.id, b.x, b.y FROM orexp_a a, orexp_b b
+WHERE a.id = b.x OR a.id = b.y
+LIMIT 2;
+ QUERY PLAN
+-----------------------------------------------------
+ Limit
+ -> Nested Loop
+ Join Filter: ((a.id = b.x) OR (a.id = b.y))
+ -> Seq Scan on orexp_a a
+ -> Materialize
+ -> Seq Scan on orexp_b b
+(6 rows)
+
+-- GROUP BY and aggregate atop expanded join
+EXPLAIN (COSTS OFF)
+SELECT a.id, count(*), sum(b.val) FROM orexp_a a, orexp_b b
+WHERE a.id = b.x OR a.id = b.y
+GROUP BY a.id
+ORDER BY a.id;
+ QUERY PLAN
+-----------------------------------------------------------------
+ Sort
+ Sort Key: a.id
+ -> HashAggregate
+ Group Key: a.id
+ -> Append
+ -> Merge Join
+ Merge Cond: (b.x = a.id)
+ -> Sort
+ Sort Key: b.x
+ -> Seq Scan on orexp_b b
+ -> Sort
+ Sort Key: a.id
+ -> Seq Scan on orexp_a a
+ -> Merge Join
+ Merge Cond: (b_1.y = a_1.id)
+ Join Filter: ((a_1.id = b_1.x) IS NOT TRUE)
+ -> Sort
+ Sort Key: b_1.y
+ -> Seq Scan on orexp_b b_1
+ -> Sort
+ Sort Key: a_1.id
+ -> Seq Scan on orexp_a a_1
+(22 rows)
+
+SELECT a.id, count(*), sum(b.val) FROM orexp_a a, orexp_b b
+WHERE a.id = b.x OR a.id = b.y
+GROUP BY a.id
+ORDER BY a.id;
+ id | count | sum
+----+-------+-----
+ 1 | 1 | 100
+ 2 | 1 | 200
+ 3 | 1 | 300
+ 4 | 1 | 400
+(4 rows)
+
+-- Zero-column target (count(*))
+EXPLAIN (COSTS OFF)
+SELECT count(*) FROM orexp_a a, orexp_b b
+WHERE a.id = b.x OR a.id = b.y;
+ QUERY PLAN
+-----------------------------------------------------------
+ Aggregate
+ -> Append
+ -> Merge Join
+ Merge Cond: (b.x = a.id)
+ -> Sort
+ Sort Key: b.x
+ -> Seq Scan on orexp_b b
+ -> Sort
+ Sort Key: a.id
+ -> Seq Scan on orexp_a a
+ -> Merge Join
+ Merge Cond: (b_1.y = a_1.id)
+ Join Filter: ((a_1.id = b_1.x) IS NOT TRUE)
+ -> Sort
+ Sort Key: b_1.y
+ -> Seq Scan on orexp_b b_1
+ -> Sort
+ Sort Key: a_1.id
+ -> Seq Scan on orexp_a a_1
+(19 rows)
+
+SELECT count(*) FROM orexp_a a, orexp_b b
+WHERE a.id = b.x OR a.id = b.y;
+ count
+-------
+ 4
+(1 row)
+
+--
+-- Outer joins
+--
+-- LEFT JOIN where WHERE clause contains cross-relation disjunction
+EXPLAIN (COSTS OFF)
+SELECT a.id, b.x, b.y FROM orexp_a a LEFT JOIN orexp_b b ON a.id = b.x
+WHERE b.val = 100 OR a.id = 2
+ORDER BY 1, 2, 3;
+ QUERY PLAN
+-----------------------------------------------------
+ Sort
+ Sort Key: a.id, b.x, b.y
+ -> Append
+ -> Hash Join
+ Hash Cond: (a.id = b.x)
+ -> Seq Scan on orexp_a a
+ -> Hash
+ -> Seq Scan on orexp_b b
+ Filter: (val = 100)
+ -> Nested Loop Left Join
+ Filter: ((b_1.val = 100) IS NOT TRUE)
+ -> Seq Scan on orexp_a a_1
+ Filter: (id = 2)
+ -> Materialize
+ -> Seq Scan on orexp_b b_1
+ Filter: (x = 2)
+(16 rows)
+
+SELECT a.id, b.x, b.y FROM orexp_a a LEFT JOIN orexp_b b ON a.id = b.x
+WHERE b.val = 100 OR a.id = 2
+ORDER BY 1, 2, 3;
+ id | x | y
+----+---+----
+ 1 | 1 | 99
+ 2 | |
+(2 rows)
+
+-- FULL JOIN reduced to INNER join by strict WHERE quals
+EXPLAIN (COSTS OFF)
+SELECT a.id, b.y FROM orexp_a a FULL JOIN orexp_b b ON a.id = b.x
+WHERE a.id = b.y OR b.x = a.id
+ORDER BY 1, 2;
+ QUERY PLAN
+-----------------------------------------------------
+ Incremental Sort
+ Sort Key: a.id, b.y
+ Presorted Key: a.id
+ -> Merge Join
+ Merge Cond: (b.x = a.id)
+ Join Filter: ((a.id = b.y) OR (b.x = a.id))
+ -> Sort
+ Sort Key: b.x
+ -> Seq Scan on orexp_b b
+ -> Sort
+ Sort Key: a.id
+ -> Seq Scan on orexp_a a
+(12 rows)
+
+SELECT a.id, b.y FROM orexp_a a FULL JOIN orexp_b b ON a.id = b.x
+WHERE a.id = b.y OR b.x = a.id
+ORDER BY 1, 2;
+ id | y
+----+----
+ 1 | 99
+ 3 | 3
+ 4 | 99
+(3 rows)
+
+--
+-- Subqueries and derived tables
+--
+-- Pulled-up subquery participating in disjunction
+EXPLAIN (COSTS OFF)
+SELECT sub.id, b.y FROM (SELECT id, val FROM orexp_a) sub, orexp_b b
+WHERE sub.id = b.x OR sub.val = b.y
+ORDER BY 1, 2;
+ QUERY PLAN
+-----------------------------------------------------------------
+ Sort
+ Sort Key: orexp_a.id, b.y
+ -> Append
+ -> Merge Join
+ Merge Cond: (b.x = orexp_a.id)
+ -> Sort
+ Sort Key: b.x
+ -> Seq Scan on orexp_b b
+ -> Sort
+ Sort Key: orexp_a.id
+ -> Seq Scan on orexp_a
+ -> Merge Join
+ Merge Cond: (b_1.y = orexp_a_1.val)
+ Join Filter: ((orexp_a_1.id = b_1.x) IS NOT TRUE)
+ -> Sort
+ Sort Key: b_1.y
+ -> Seq Scan on orexp_b b_1
+ -> Sort
+ Sort Key: orexp_a_1.val
+ -> Seq Scan on orexp_a orexp_a_1
+(20 rows)
+
+SELECT sub.id, b.y FROM (SELECT id, val FROM orexp_a) sub, orexp_b b
+WHERE sub.id = b.x OR sub.val = b.y
+ORDER BY 1, 2;
+ id | y
+----+----
+ 1 | 99
+ 3 | 3
+ 4 | 99
+(3 rows)
+
+-- Derived table from VALUES list
+EXPLAIN (COSTS OFF)
+SELECT v.a, b.y FROM (VALUES (1, 99), (2, NULL), (3, 3)) v(a, b), orexp_b b
+WHERE v.a = b.x OR v.b = b.y
+ORDER BY 1, 2;
+ QUERY PLAN
+-------------------------------------------------------------------------
+ Sort
+ Sort Key: "*VALUES*".column1, b.y
+ -> Append
+ -> Hash Join
+ Hash Cond: (b.x = "*VALUES*".column1)
+ -> Seq Scan on orexp_b b
+ -> Hash
+ -> Values Scan on "*VALUES*"
+ -> Hash Join
+ Hash Cond: (b_1.y = "*VALUES*_1".column2)
+ Join Filter: (("*VALUES*_1".column1 = b_1.x) IS NOT TRUE)
+ -> Seq Scan on orexp_b b_1
+ -> Hash
+ -> Values Scan on "*VALUES*_1"
+(14 rows)
+
+SELECT v.a, b.y FROM (VALUES (1, 99), (2, NULL), (3, 3)) v(a, b), orexp_b b
+WHERE v.a = b.x OR v.b = b.y
+ORDER BY 1, 2;
+ a | y
+---+----
+ 1 | 99
+ 1 | 99
+ 1 | 99
+ 3 | 3
+(4 rows)
+
+--
+-- Partitioned and inheritance tables
+--
+-- Partitioned table
+CREATE TABLE orexp_part (id int, d int) PARTITION BY RANGE (d);
+CREATE TABLE orexp_part1 PARTITION OF orexp_part FOR VALUES FROM (0) TO (10);
+CREATE TABLE orexp_part2 PARTITION OF orexp_part FOR VALUES FROM (10) TO (20);
+INSERT INTO orexp_part VALUES (1, 5), (2, 15);
+EXPLAIN (COSTS OFF)
+SELECT a.id, p.d FROM orexp_a a, orexp_part p
+WHERE a.id = p.id OR a.val = p.d;
+ QUERY PLAN
+------------------------------------------------------
+ Append
+ -> Merge Join
+ Merge Cond: (a.id = p.id)
+ -> Sort
+ Sort Key: a.id
+ -> Seq Scan on orexp_a a
+ -> Sort
+ Sort Key: p.id
+ -> Append
+ -> Seq Scan on orexp_part1 p_1
+ -> Seq Scan on orexp_part2 p_2
+ -> Merge Join
+ Merge Cond: (a_1.val = p_3.d)
+ Join Filter: ((a_1.id = p_3.id) IS NOT TRUE)
+ -> Sort
+ Sort Key: a_1.val
+ -> Seq Scan on orexp_a a_1
+ -> Sort
+ Sort Key: p_3.d
+ -> Append
+ -> Seq Scan on orexp_part1 p_4
+ -> Seq Scan on orexp_part2 p_5
+(22 rows)
+
+DROP TABLE orexp_part;
+-- Table inheritance
+CREATE TABLE orexp_inh_parent (id int, val int);
+CREATE TABLE orexp_inh_child () INHERITS (orexp_inh_parent);
+INSERT INTO orexp_inh_parent VALUES (1, 10);
+INSERT INTO orexp_inh_child VALUES (2, 20);
+EXPLAIN (COSTS OFF)
+SELECT a.id, p.val FROM orexp_a a, orexp_inh_parent p
+WHERE a.id = p.id OR a.val = p.val;
+ QUERY PLAN
+----------------------------------------------------------
+ Append
+ -> Merge Join
+ Merge Cond: (a.id = p.id)
+ -> Sort
+ Sort Key: a.id
+ -> Seq Scan on orexp_a a
+ -> Sort
+ Sort Key: p.id
+ -> Append
+ -> Seq Scan on orexp_inh_parent p_1
+ -> Seq Scan on orexp_inh_child p_2
+ -> Merge Join
+ Merge Cond: (a_1.val = p_3.val)
+ Join Filter: ((a_1.id = p_3.id) IS NOT TRUE)
+ -> Sort
+ Sort Key: a_1.val
+ -> Seq Scan on orexp_a a_1
+ -> Sort
+ Sort Key: p_3.val
+ -> Append
+ -> Seq Scan on orexp_inh_parent p_4
+ -> Seq Scan on orexp_inh_child p_5
+(22 rows)
+
+DROP TABLE orexp_inh_parent CASCADE;
+NOTICE: drop cascades to table orexp_inh_child
+--
+-- Parallel Append
+--
+-- Encourage parallel query and parallel append
+BEGIN;
+SET LOCAL parallel_setup_cost = 0;
+SET LOCAL parallel_tuple_cost = 0;
+SET LOCAL min_parallel_table_scan_size = 0;
+SET LOCAL max_parallel_workers_per_gather = 2;
+SET LOCAL enable_parallel_append = on;
+EXPLAIN (COSTS OFF)
+SELECT a.id, b.x, b.y FROM orexp_a a, orexp_b b
+WHERE a.id = b.x OR a.id = b.y
+ORDER BY a.id, b.x, b.y;
+ QUERY PLAN
+----------------------------------------------------------------
+ Gather Merge
+ Workers Planned: 2
+ -> Sort
+ Sort Key: a.id, b.x, b.y
+ -> Parallel Append
+ -> Parallel Hash Join
+ Hash Cond: (a.id = b.y)
+ Join Filter: ((a.id = b.x) IS NOT TRUE)
+ -> Parallel Seq Scan on orexp_a a
+ -> Parallel Hash
+ -> Parallel Seq Scan on orexp_b b
+ -> Parallel Hash Join
+ Hash Cond: (a_1.id = b_1.x)
+ -> Parallel Seq Scan on orexp_a a_1
+ -> Parallel Hash
+ -> Parallel Seq Scan on orexp_b b_1
+(16 rows)
+
+SELECT a.id, b.x, b.y FROM orexp_a a, orexp_b b
+WHERE a.id = b.x OR a.id = b.y
+ORDER BY a.id, b.x, b.y;
+ id | x | y
+----+----+----
+ 1 | 1 | 99
+ 2 | 99 | 2
+ 3 | 3 | 3
+ 4 | 4 | 99
+(4 rows)
+
+COMMIT;
+--
+-- Pulled-up UNION ALL append relation
+--
+EXPLAIN (COSTS OFF)
+SELECT u.id, a.val FROM (SELECT x AS id, val FROM orexp_b
+ UNION ALL
+ SELECT id, val FROM orexp_a) u, orexp_a a
+WHERE u.val = a.val OR u.id = a.id
+ORDER BY u.id, a.val;
+ QUERY PLAN
+--------------------------------------------------------------------
+ Sort
+ Sort Key: orexp_b.x, a.val
+ -> Append
+ -> Merge Join
+ Merge Cond: (a.val = orexp_b.val)
+ -> Sort
+ Sort Key: a.val
+ -> Seq Scan on orexp_a a
+ -> Sort
+ Sort Key: orexp_b.val
+ -> Append
+ -> Seq Scan on orexp_b
+ -> Seq Scan on orexp_a
+ -> Merge Join
+ Merge Cond: (a_1.id = orexp_b_1.x)
+ Join Filter: ((orexp_b_1.val = a_1.val) IS NOT TRUE)
+ -> Sort
+ Sort Key: a_1.id
+ -> Seq Scan on orexp_a a_1
+ -> Sort
+ Sort Key: orexp_b_1.x
+ -> Append
+ -> Seq Scan on orexp_b orexp_b_1
+ -> Seq Scan on orexp_a orexp_a_1
+(24 rows)
+
+SELECT u.id, a.val FROM (SELECT x AS id, val FROM orexp_b
+ UNION ALL
+ SELECT id, val FROM orexp_a) u, orexp_a a
+WHERE u.val = a.val OR u.id = a.id
+ORDER BY u.id, a.val;
+ id | val
+----+-----
+ 1 | 10
+ 1 | 10
+ 2 | 20
+ 3 | 30
+ 3 | 30
+ 4 |
+ 4 |
+ 5 | 50
+(8 rows)
+
+--
+-- LATERAL reference
+--
+EXPLAIN (COSTS OFF)
+SELECT a.id, l.ly FROM orexp_a a,
+ LATERAL (SELECT b.y AS ly FROM orexp_b b WHERE b.x = a.id OR b.y = a.val) l
+WHERE a.id = l.ly OR a.val = 1
+ORDER BY a.id, l.ly;
+ QUERY PLAN
+---------------------------------------------------------------------------------------------------------
+ Sort
+ Sort Key: a.id, b.y
+ -> Append
+ -> Merge Join
+ Merge Cond: (b.y = a.id)
+ Join Filter: ((b.x = a.id) OR (b.y = a.val))
+ -> Sort
+ Sort Key: b.y
+ -> Seq Scan on orexp_b b
+ -> Sort
+ Sort Key: a.id
+ -> Seq Scan on orexp_a a
+ -> Nested Loop
+ Join Filter: (((a_1.id = b_1.y) IS NOT TRUE) AND ((b_1.x = a_1.id) OR (b_1.y = a_1.val)))
+ -> Seq Scan on orexp_b b_1
+ -> Materialize
+ -> Seq Scan on orexp_a a_1
+ Filter: (val = 1)
+(18 rows)
+
+SELECT a.id, l.ly FROM orexp_a a,
+ LATERAL (SELECT b.y AS ly FROM orexp_b b WHERE b.x = a.id OR b.y = a.val) l
+WHERE a.id = l.ly OR a.val = 1
+ORDER BY a.id, l.ly;
+ id | ly
+----+----
+ 3 | 3
+(1 row)
+
+--
+-- Ineligible queries (safety gates correctly bypass expansion)
+--
+-- Volatile function in WHERE
+EXPLAIN (COSTS OFF)
+SELECT a.id, b.y FROM orexp_a a, orexp_b b
+WHERE a.id = b.x OR (a.id = b.y AND random() < 0.5);
+ QUERY PLAN
+------------------------------------------------------------------------------------------
+ Nested Loop
+ Join Filter: ((a.id = b.x) OR ((a.id = b.y) AND (random() < '0.5'::double precision)))
+ -> Seq Scan on orexp_a a
+ -> Materialize
+ -> Seq Scan on orexp_b b
+(5 rows)
+
+-- Correlated SubPlan in WHERE
+EXPLAIN (COSTS OFF)
+SELECT a.id, b.y FROM orexp_a a, orexp_b b
+WHERE (a.id = b.x OR a.id = b.y)
+ AND a.val > (SELECT max(b2.val) FROM orexp_b b2 WHERE b2.x = a.id);
+ QUERY PLAN
+--------------------------------------------------
+ Nested Loop
+ Join Filter: ((a.id = b.x) OR (a.id = b.y))
+ -> Seq Scan on orexp_b b
+ -> Materialize
+ -> Seq Scan on orexp_a a
+ Filter: (val > (SubPlan expr_1))
+ SubPlan expr_1
+ -> Aggregate
+ -> Seq Scan on orexp_b b2
+ Filter: (x = a.id)
+(10 rows)
+
+-- TABLESAMPLE
+EXPLAIN (COSTS OFF)
+SELECT a.id, b.y FROM orexp_a a, orexp_b b TABLESAMPLE SYSTEM (50)
+WHERE a.id = b.x OR a.id = b.y;
+ QUERY PLAN
+-----------------------------------------------
+ Nested Loop
+ Join Filter: ((a.id = b.x) OR (a.id = b.y))
+ -> Seq Scan on orexp_a a
+ -> Materialize
+ -> Sample Scan on orexp_b b
+ Sampling: system ('50'::real)
+(6 rows)
+
+-- Unreduced FULL JOIN
+EXPLAIN (COSTS OFF)
+SELECT a.id, b.y FROM orexp_a a FULL JOIN orexp_b b ON a.id = b.x
+WHERE a.val IS NULL OR b.val IS NULL;
+ QUERY PLAN
+------------------------------------------------
+ Merge Full Join
+ Merge Cond: (b.x = a.id)
+ Filter: ((a.val IS NULL) OR (b.val IS NULL))
+ -> Sort
+ Sort Key: b.x
+ -> Seq Scan on orexp_b b
+ -> Sort
+ Sort Key: a.id
+ -> Seq Scan on orexp_a a
+(9 rows)
+
+-- Active unflattened subquery with grouping
+EXPLAIN (COSTS OFF)
+SELECT a.id, s.n FROM orexp_a a,
+ (SELECT x AS sx, count(*) AS n FROM orexp_b GROUP BY x) s
+WHERE a.id = s.sx OR a.val = s.n;
+ QUERY PLAN
+-------------------------------------------------
+ Nested Loop
+ Join Filter: ((a.id = s.sx) OR (a.val = s.n))
+ -> Seq Scan on orexp_a a
+ -> Materialize
+ -> Subquery Scan on s
+ -> HashAggregate
+ Group Key: orexp_b.x
+ -> Seq Scan on orexp_b
+(8 rows)
+
+--
+-- GUC limit control
+--
+-- Arm count exceeds limit: expansion skipped
+SET or_expansion_limit = 2;
+EXPLAIN (COSTS OFF)
+SELECT a.id, b.x, b.y, b.val FROM orexp_a a, orexp_b b
+WHERE a.id = b.x OR a.id = b.y OR a.val = b.val
+ORDER BY a.id, b.x, b.y, b.val;
+ QUERY PLAN
+------------------------------------------------------------------------
+ Sort
+ Sort Key: a.id, b.x, b.y, b.val
+ -> Nested Loop
+ Join Filter: ((a.id = b.x) OR (a.id = b.y) OR (a.val = b.val))
+ -> Seq Scan on orexp_a a
+ -> Materialize
+ -> Seq Scan on orexp_b b
+(7 rows)
+
+-- Arm count within limit: expansion applied
+SET or_expansion_limit = 3;
+EXPLAIN (COSTS OFF)
+SELECT a.id, b.x, b.y, b.val FROM orexp_a a, orexp_b b
+WHERE a.id = b.x OR a.id = b.y OR a.val = b.val
+ORDER BY a.id, b.x, b.y, b.val;
+ QUERY PLAN
+------------------------------------------------------------------------------------------------
+ Sort
+ Sort Key: a.id, b.x, b.y, b.val
+ -> Append
+ -> Merge Join
+ Merge Cond: (b.x = a.id)
+ -> Sort
+ Sort Key: b.x
+ -> Seq Scan on orexp_b b
+ -> Sort
+ Sort Key: a.id
+ -> Seq Scan on orexp_a a
+ -> Merge Join
+ Merge Cond: (b_1.y = a_1.id)
+ Join Filter: ((a_1.id = b_1.x) IS NOT TRUE)
+ -> Sort
+ Sort Key: b_1.y
+ -> Seq Scan on orexp_b b_1
+ -> Sort
+ Sort Key: a_1.id
+ -> Seq Scan on orexp_a a_1
+ -> Merge Join
+ Merge Cond: (b_2.val = a_2.val)
+ Join Filter: (((a_2.id = b_2.x) IS NOT TRUE) AND ((a_2.id = b_2.y) IS NOT TRUE))
+ -> Sort
+ Sort Key: b_2.val
+ -> Seq Scan on orexp_b b_2
+ -> Sort
+ Sort Key: a_2.val
+ -> Seq Scan on orexp_a a_2
+(29 rows)
+
+SELECT a.id, b.x, b.y, b.val FROM orexp_a a, orexp_b b
+WHERE a.id = b.x OR a.id = b.y OR a.val = b.val
+ORDER BY a.id, b.x, b.y, b.val;
+ id | x | y | val
+----+----+----+-----
+ 1 | 1 | 99 | 100
+ 2 | 99 | 2 | 200
+ 3 | 3 | 3 | 300
+ 4 | 4 | 99 | 400
+(4 rows)
+
+RESET or_expansion_limit;
+--
+-- Clean up
+--
+DROP TABLE orexp_a, orexp_b;
diff --git a/src/test/regress/parallel_schedule b/src/test/regress/parallel_schedule
index bb13a7b6b8f..6bbda17968c 100644
--- a/src/test/regress/parallel_schedule
+++ b/src/test/regress/parallel_schedule
@@ -128,7 +128,7 @@ test: rowtypes_alter
# The stats test resets stats, so nothing else needing stats access can be in
# this group.
# ----------
-test: partition_join partition_prune reloptions hash_part indexing partition_aggregate partition_info tuplesort explain memoize stats predicate numa eager_aggregate planner_est attribute_version
+test: partition_join partition_prune reloptions hash_part indexing partition_aggregate partition_info tuplesort explain memoize stats predicate numa eager_aggregate planner_est attribute_version or_expansion
# ----------
# Another group of parallel tests (compression)
diff --git a/src/test/regress/sql/join.sql b/src/test/regress/sql/join.sql
index 45dcd48d2b3..41d555664e6 100644
--- a/src/test/regress/sql/join.sql
+++ b/src/test/regress/sql/join.sql
@@ -5080,12 +5080,16 @@ WHERE ss.unique1 = ss.phv AND t1.unique1 < 100;
-- to SAOP.
--
+SET or_expansion_limit = 0;
+
EXPLAIN (COSTS OFF)
SELECT COUNT(*) FROM tenk1 t1, tenk1 t2
WHERE t2.thousand = t1.tenthous OR t2.thousand = t1.unique1 OR t2.thousand = t1.unique2;
SELECT COUNT(*) FROM tenk1 t1, tenk1 t2
WHERE t2.thousand = t1.tenthous OR t2.thousand = t1.unique1 OR t2.thousand = t1.unique2;
+RESET or_expansion_limit;
+
EXPLAIN (COSTS OFF)
SELECT COUNT(*) FROM onek t1 LEFT JOIN tenk1 t2
ON (t2.thousand = t1.tenthous OR t2.thousand = t1.thousand);
diff --git a/src/test/regress/sql/or_expansion.sql b/src/test/regress/sql/or_expansion.sql
new file mode 100644
index 00000000000..d6e6dd7f88f
--- /dev/null
+++ b/src/test/regress/sql/or_expansion.sql
@@ -0,0 +1,326 @@
+--
+-- Tests for OR-clause expansion into UNION ALL Append paths
+--
+
+-- Initial GUC check
+SHOW or_expansion_limit;
+
+CREATE TABLE orexp_a (id int, val int);
+CREATE TABLE orexp_b (x int, y int, val int);
+
+INSERT INTO orexp_a VALUES
+ (1, 10),
+ (2, 20),
+ (3, 30),
+ (4, NULL),
+ (5, 50);
+
+INSERT INTO orexp_b VALUES
+ (1, 99, 100),
+ (99, 2, 200),
+ (3, 3, 300),
+ (4, 99, 400),
+ (99, 99, 500),
+ (NULL, NULL, 600);
+
+--
+-- Basic OR-clause expansion
+--
+
+-- Disjunction on join keys across two tables
+EXPLAIN (COSTS OFF)
+SELECT a.id, b.x, b.y FROM orexp_a a, orexp_b b
+WHERE a.id = b.x OR a.id = b.y
+ORDER BY a.id, b.x, b.y;
+
+SELECT a.id, b.x, b.y FROM orexp_a a, orexp_b b
+WHERE a.id = b.x OR a.id = b.y
+ORDER BY a.id, b.x, b.y;
+
+-- Compare with expansion disabled to confirm semantic equivalence
+SET or_expansion_limit = 0;
+
+EXPLAIN (COSTS OFF)
+SELECT a.id, b.x, b.y FROM orexp_a a, orexp_b b
+WHERE a.id = b.x OR a.id = b.y
+ORDER BY a.id, b.x, b.y;
+
+SELECT a.id, b.x, b.y FROM orexp_a a, orexp_b b
+WHERE a.id = b.x OR a.id = b.y
+ORDER BY a.id, b.x, b.y;
+
+RESET or_expansion_limit;
+
+--
+-- Three-valued logic and duplicate elimination
+--
+-- Row (3, 30) from orexp_a and (3, 3, 300) from orexp_b satisfies both arms:
+-- a.id = b.x (3 = 3) AND a.id = b.y (3 = 3).
+-- The (a.id = b.x) IS NOT TRUE exclusion condition in the second arm ensures
+-- it is emitted exactly once. Rows with NULLs are correctly handled.
+EXPLAIN (COSTS OFF)
+SELECT a.id, a.val, b.x, b.y, b.val
+FROM orexp_a a, orexp_b b
+WHERE (a.id = b.x OR a.id = b.y) AND (a.val IS NOT NULL OR b.val > 200)
+ORDER BY a.id, b.x, b.y;
+
+SELECT a.id, a.val, b.x, b.y, b.val
+FROM orexp_a a, orexp_b b
+WHERE (a.id = b.x OR a.id = b.y) AND (a.val IS NOT NULL OR b.val > 200)
+ORDER BY a.id, b.x, b.y;
+
+--
+-- Multi-arm expansion (3 arms)
+--
+-- Arm 2 excludes Arm 0; Arm 3 excludes both Arm 0 and Arm 1.
+EXPLAIN (COSTS OFF)
+SELECT a.id, b.x, b.y, b.val FROM orexp_a a, orexp_b b
+WHERE a.id = b.x OR a.id = b.y OR a.val = b.val
+ORDER BY a.id, b.x, b.y, b.val;
+
+SELECT a.id, b.x, b.y, b.val FROM orexp_a a, orexp_b b
+WHERE a.id = b.x OR a.id = b.y OR a.val = b.val
+ORDER BY a.id, b.x, b.y, b.val;
+
+--
+-- Target list projection and expressions
+--
+
+-- Column order differs from scan order and includes cross-table expressions
+EXPLAIN (COSTS OFF)
+SELECT b.y, a.id + b.x AS sum_id_x, a.val, 'tag' AS literal
+FROM orexp_a a, orexp_b b
+WHERE a.id = b.x OR a.id = b.y
+ORDER BY sum_id_x, b.y;
+
+SELECT b.y, a.id + b.x AS sum_id_x, a.val, 'tag' AS literal
+FROM orexp_a a, orexp_b b
+WHERE a.id = b.x OR a.id = b.y
+ORDER BY sum_id_x, b.y;
+
+-- Whole-row references
+EXPLAIN (COSTS OFF)
+SELECT a.*, b.* FROM orexp_a a, orexp_b b
+WHERE a.id = b.x OR a.id = b.y
+ORDER BY a.id, b.x, b.y;
+
+--
+-- Upper planner nodes and cost propagation
+--
+
+-- Fast-start with LIMIT: tuple_fraction and limit_tuples passed to arms
+EXPLAIN (COSTS OFF)
+SELECT a.id, b.x, b.y FROM orexp_a a, orexp_b b
+WHERE a.id = b.x OR a.id = b.y
+LIMIT 2;
+
+-- GROUP BY and aggregate atop expanded join
+EXPLAIN (COSTS OFF)
+SELECT a.id, count(*), sum(b.val) FROM orexp_a a, orexp_b b
+WHERE a.id = b.x OR a.id = b.y
+GROUP BY a.id
+ORDER BY a.id;
+
+SELECT a.id, count(*), sum(b.val) FROM orexp_a a, orexp_b b
+WHERE a.id = b.x OR a.id = b.y
+GROUP BY a.id
+ORDER BY a.id;
+
+-- Zero-column target (count(*))
+EXPLAIN (COSTS OFF)
+SELECT count(*) FROM orexp_a a, orexp_b b
+WHERE a.id = b.x OR a.id = b.y;
+
+SELECT count(*) FROM orexp_a a, orexp_b b
+WHERE a.id = b.x OR a.id = b.y;
+
+--
+-- Outer joins
+--
+
+-- LEFT JOIN where WHERE clause contains cross-relation disjunction
+EXPLAIN (COSTS OFF)
+SELECT a.id, b.x, b.y FROM orexp_a a LEFT JOIN orexp_b b ON a.id = b.x
+WHERE b.val = 100 OR a.id = 2
+ORDER BY 1, 2, 3;
+
+SELECT a.id, b.x, b.y FROM orexp_a a LEFT JOIN orexp_b b ON a.id = b.x
+WHERE b.val = 100 OR a.id = 2
+ORDER BY 1, 2, 3;
+
+-- FULL JOIN reduced to INNER join by strict WHERE quals
+EXPLAIN (COSTS OFF)
+SELECT a.id, b.y FROM orexp_a a FULL JOIN orexp_b b ON a.id = b.x
+WHERE a.id = b.y OR b.x = a.id
+ORDER BY 1, 2;
+
+SELECT a.id, b.y FROM orexp_a a FULL JOIN orexp_b b ON a.id = b.x
+WHERE a.id = b.y OR b.x = a.id
+ORDER BY 1, 2;
+
+--
+-- Subqueries and derived tables
+--
+
+-- Pulled-up subquery participating in disjunction
+EXPLAIN (COSTS OFF)
+SELECT sub.id, b.y FROM (SELECT id, val FROM orexp_a) sub, orexp_b b
+WHERE sub.id = b.x OR sub.val = b.y
+ORDER BY 1, 2;
+
+SELECT sub.id, b.y FROM (SELECT id, val FROM orexp_a) sub, orexp_b b
+WHERE sub.id = b.x OR sub.val = b.y
+ORDER BY 1, 2;
+
+-- Derived table from VALUES list
+EXPLAIN (COSTS OFF)
+SELECT v.a, b.y FROM (VALUES (1, 99), (2, NULL), (3, 3)) v(a, b), orexp_b b
+WHERE v.a = b.x OR v.b = b.y
+ORDER BY 1, 2;
+
+SELECT v.a, b.y FROM (VALUES (1, 99), (2, NULL), (3, 3)) v(a, b), orexp_b b
+WHERE v.a = b.x OR v.b = b.y
+ORDER BY 1, 2;
+
+--
+-- Partitioned and inheritance tables
+--
+
+-- Partitioned table
+CREATE TABLE orexp_part (id int, d int) PARTITION BY RANGE (d);
+CREATE TABLE orexp_part1 PARTITION OF orexp_part FOR VALUES FROM (0) TO (10);
+CREATE TABLE orexp_part2 PARTITION OF orexp_part FOR VALUES FROM (10) TO (20);
+INSERT INTO orexp_part VALUES (1, 5), (2, 15);
+
+EXPLAIN (COSTS OFF)
+SELECT a.id, p.d FROM orexp_a a, orexp_part p
+WHERE a.id = p.id OR a.val = p.d;
+
+DROP TABLE orexp_part;
+
+-- Table inheritance
+CREATE TABLE orexp_inh_parent (id int, val int);
+CREATE TABLE orexp_inh_child () INHERITS (orexp_inh_parent);
+INSERT INTO orexp_inh_parent VALUES (1, 10);
+INSERT INTO orexp_inh_child VALUES (2, 20);
+
+EXPLAIN (COSTS OFF)
+SELECT a.id, p.val FROM orexp_a a, orexp_inh_parent p
+WHERE a.id = p.id OR a.val = p.val;
+
+DROP TABLE orexp_inh_parent CASCADE;
+
+--
+-- Parallel Append
+--
+
+-- Encourage parallel query and parallel append
+BEGIN;
+SET LOCAL parallel_setup_cost = 0;
+SET LOCAL parallel_tuple_cost = 0;
+SET LOCAL min_parallel_table_scan_size = 0;
+SET LOCAL max_parallel_workers_per_gather = 2;
+SET LOCAL enable_parallel_append = on;
+
+EXPLAIN (COSTS OFF)
+SELECT a.id, b.x, b.y FROM orexp_a a, orexp_b b
+WHERE a.id = b.x OR a.id = b.y
+ORDER BY a.id, b.x, b.y;
+
+SELECT a.id, b.x, b.y FROM orexp_a a, orexp_b b
+WHERE a.id = b.x OR a.id = b.y
+ORDER BY a.id, b.x, b.y;
+
+COMMIT;
+
+--
+-- Pulled-up UNION ALL append relation
+--
+
+EXPLAIN (COSTS OFF)
+SELECT u.id, a.val FROM (SELECT x AS id, val FROM orexp_b
+ UNION ALL
+ SELECT id, val FROM orexp_a) u, orexp_a a
+WHERE u.val = a.val OR u.id = a.id
+ORDER BY u.id, a.val;
+
+SELECT u.id, a.val FROM (SELECT x AS id, val FROM orexp_b
+ UNION ALL
+ SELECT id, val FROM orexp_a) u, orexp_a a
+WHERE u.val = a.val OR u.id = a.id
+ORDER BY u.id, a.val;
+
+--
+-- LATERAL reference
+--
+
+EXPLAIN (COSTS OFF)
+SELECT a.id, l.ly FROM orexp_a a,
+ LATERAL (SELECT b.y AS ly FROM orexp_b b WHERE b.x = a.id OR b.y = a.val) l
+WHERE a.id = l.ly OR a.val = 1
+ORDER BY a.id, l.ly;
+
+SELECT a.id, l.ly FROM orexp_a a,
+ LATERAL (SELECT b.y AS ly FROM orexp_b b WHERE b.x = a.id OR b.y = a.val) l
+WHERE a.id = l.ly OR a.val = 1
+ORDER BY a.id, l.ly;
+
+--
+-- Ineligible queries (safety gates correctly bypass expansion)
+--
+
+-- Volatile function in WHERE
+EXPLAIN (COSTS OFF)
+SELECT a.id, b.y FROM orexp_a a, orexp_b b
+WHERE a.id = b.x OR (a.id = b.y AND random() < 0.5);
+
+-- Correlated SubPlan in WHERE
+EXPLAIN (COSTS OFF)
+SELECT a.id, b.y FROM orexp_a a, orexp_b b
+WHERE (a.id = b.x OR a.id = b.y)
+ AND a.val > (SELECT max(b2.val) FROM orexp_b b2 WHERE b2.x = a.id);
+
+-- TABLESAMPLE
+EXPLAIN (COSTS OFF)
+SELECT a.id, b.y FROM orexp_a a, orexp_b b TABLESAMPLE SYSTEM (50)
+WHERE a.id = b.x OR a.id = b.y;
+
+-- Unreduced FULL JOIN
+EXPLAIN (COSTS OFF)
+SELECT a.id, b.y FROM orexp_a a FULL JOIN orexp_b b ON a.id = b.x
+WHERE a.val IS NULL OR b.val IS NULL;
+
+-- Active unflattened subquery with grouping
+EXPLAIN (COSTS OFF)
+SELECT a.id, s.n FROM orexp_a a,
+ (SELECT x AS sx, count(*) AS n FROM orexp_b GROUP BY x) s
+WHERE a.id = s.sx OR a.val = s.n;
+
+--
+-- GUC limit control
+--
+
+-- Arm count exceeds limit: expansion skipped
+SET or_expansion_limit = 2;
+EXPLAIN (COSTS OFF)
+SELECT a.id, b.x, b.y, b.val FROM orexp_a a, orexp_b b
+WHERE a.id = b.x OR a.id = b.y OR a.val = b.val
+ORDER BY a.id, b.x, b.y, b.val;
+
+-- Arm count within limit: expansion applied
+SET or_expansion_limit = 3;
+EXPLAIN (COSTS OFF)
+SELECT a.id, b.x, b.y, b.val FROM orexp_a a, orexp_b b
+WHERE a.id = b.x OR a.id = b.y OR a.val = b.val
+ORDER BY a.id, b.x, b.y, b.val;
+
+SELECT a.id, b.x, b.y, b.val FROM orexp_a a, orexp_b b
+WHERE a.id = b.x OR a.id = b.y OR a.val = b.val
+ORDER BY a.id, b.x, b.y, b.val;
+
+RESET or_expansion_limit;
+
+--
+-- Clean up
+--
+DROP TABLE orexp_a, orexp_b;
--
2.34.1