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

Started by Ayoub Kazarabout 2 months ago14 messageshackers
Jump to latest
#1Ayoub Kazar
kazarayoub2004@gmail.com

Hello hackers,

Attached is a patch that lets the planner rewrite an OR clause that spans
several relations into a UNION ALL with one branch per arm, and use that
plan when it is estimated to be cheaper.

Background

OR clauses that mention more than one relation are awkward for the planner
today. If the OR is the join condition itself (a.x = b.y OR a.x = b.z), it
cannot be a hash or merge join clause, so the only choice left is a nested
loop, usually with a BitmapOr of index scans on the inner side that is run
again for every outer row. If it is a filter on two different tables
(a.f = 1 OR b.g = 2), BitmapOr cannot help either, since it only combines
indexes of one relation, and the OR ends up as a join filter. The
textbook case is a star schema with an OR over conditions on two
dimension tables.

I ran into this while working on undirected edge patterns in SQL/PGQ
[1]: /messages/by-id/4ab664c3585d3c2da2d4c1d1bbed430e@data-bene.io
edge in the join condition, and on LSQB the nested loop
with the per-row BitmapOr ran the inner scan about 61 million times at SF
0.1. Writing the same query by hand as a UNION ALL took it from 91.7 s to
1.6 s, and at greater scale factors it was faster by 4610x . I first
did the rewrite in the GRAPH_TABLE rewriter, but Ashutosh pointed out that
it belongs in the planner: if at any time its added, the rewrite for
SQL/PGQ would be redundant.

Previous work

There was a previous discussion on this, Tom Lane posted a patch for
this in 2017 [2]/messages/by-id/7f70bd5a-5d16-e05c-f0b4-2fdfc8873489@BlueTreble.com, in the thread . The idea is: plan the arms before
query_planner() runs and add
the result as an Append path afterwards. The differences are the way
duplicates are avoided and what is accepted. At that time it wasn't
clear how to prove correctness on deduplication (which was done with a
Unique on CTIDs of base relations), last message of the thread actually
puts the proof of doing the expansion with negating previous arms'
clauses. The latter way of doing it is far better than deduplication
with CTIDs because: we are not limited to plain tables, we don't need a
unique step.

What the patch does

For an OR with arms C1..Cn, branch k is planned as the original query with
the OR replaced by

    Ck AND (C1) IS NOT TRUE AND ... AND (C(k-1)) IS NOT TRUE

so a row that satisfies several arms is returned only by the first of
them. IS NOT TRUE (rather than NOT) keeps rows where an earlier arm
evaluates to NULL, so the result has the same rows and multiplicity as the
original query and no duplicate elimination step is needed. Each branch is
planned with query_planner() on a copy of the query, the cheapest path
of each branch is taken, and
they are combined into an Append that is added to the top scan/join
relation with add_path(). Here i followed exactly what Tom's patch did.

Outer joins are reduced again inside each branch, since the branch's
quals can make it null-rejecting.

Where it applies:

An OR in the WHERE clause with between 2 and or_expansion_limit arms that
refers to at least two relations: either the OR is the join condition, or
it is a filter spanning two tables.

    SELECT ... FROM a, b WHERE a.x = b.y OR a.x = b.z;
    SELECT ... FROM a JOIN b ON a.id = b.a_id WHERE a.f = 1 OR b.g = 2;

Where it is not considered:

- ORs that only reference one relation, the argument is that in this
case, surely a BitmapOr or anything else do the job.
- volatile functions in the jointree, security quals or function/subquery
  RTEs, since the arms are evaluated more than once
- FULL joins, TABLESAMPLE, FOR UPDATE/SHARE, CTEs, set operations,
  recursive queries, well anything other than SELECT ?
- partitioned tables, also inside subqueries. Child RTEs are created inside
  query_planner(), so after arms prune differently their range table
  indexes no longer match the original one, i didn't try to make it
work yet the solution here is maybe to refix pointers back to match root
PlannerInfo for each arm, but this felt too much, i wonder if its worth
it for the benefit it can get for partitioned tables.
- ORs in JOIN ... ON clauses. Only the top level WHERE quals are looked at
  for now.

or_expansion_limit (default 8, 0 disables) bounds the number of arms.
Every arm costs one extra planner run, and arm n carries n-1 negated copies
of the earlier arms, so planning cost can grow quickly with the number of
arms. It is also an off switch to makes before/after comparisons easy
for the moment. The
default of 8 is a nice guess because i found that starting from 7 arms,
planning time sometimes doubles (in complicated queries).

Some simlpe benchmark results

12 vCPUs, 15GB RAM, NVMe, shared_buffers = 2GB, work_mem = 128MB,
max_parallel_workers_per_gather = 2.

Star schema, 20M row fact table, OR between a condition on a customer
dimension and one on a product dimension:
    1893 ms -> 148 ms   (planning 0.26 ms -> 0.52 ms)

Two 2M row tables, selective OR with one arm on each table:
    415 ms -> 26 ms     (planning 0.94 ms -> 1.07 ms)

Three tables, three selective arms:
    891 ms -> 125 ms    (planning 1.6 ms -> 3.0 ms)

Join of two 2M row tables on (a = a OR b = b), join columns indexed,
outer side limited to id < 100k:
    1520 ms -> 435 ms   (buffer hits 57,204,110 -> 179,797)
Same with no indexes, id < 50k:
    1508 ms -> 484 ms
With id < 10k, indexed / not indexed:
    841 ms -> 417 ms  /  1538 ms -> 451 ms

Where the arms are not selective (about 20% of the rows each) the original
plans are kept.

Patch and simple benchmark files attached.

[1]: /messages/by-id/4ab664c3585d3c2da2d4c1d1bbed430e@data-bene.io
/messages/by-id/4ab664c3585d3c2da2d4c1d1bbed430e@data-bene.io
[2]: /messages/by-id/7f70bd5a-5d16-e05c-f0b4-2fdfc8873489@BlueTreble.com
/messages/by-id/7f70bd5a-5d16-e05c-f0b4-2fdfc8873489@BlueTreble.com

Regards,
Ayoub Kazar

Attachments:

t254090_1
0001-Expand-OR-clauses-in-joins-to-UNION-ALL-Append-paths.patchtext/x-patch; charset=UTF-8; name=0001-Expand-OR-clauses-in-joins-to-UNION-ALL-Append-paths.patchDownload+987-7
star_schema.sqlapplication/sql; name=star_schema.sqlDownload
or_expansion_benchmark.sqlapplication/sql; name=or_expansion_benchmark.sqlDownload
#2David Geier
geidav.pg@gmail.com
In reply to: Ayoub Kazar (#1)
Re: [PROPOSAL] Expand OR clauses in joins to UNION ALL paths

On 07.10.26 13:02, Ayoub Kazar wrote:

Attached is a patch that lets the planner rewrite an OR clause that spans
several relations into a UNION ALL with one branch per arm, and use that
plan when it is estimated to be cheaper.

Background

OR clauses that mention more than one relation are awkward for the planner
today. If the OR is the join condition itself (a.x = b.y OR a.x = b.z), it
cannot be a hash or merge join clause, so the only choice left is a nested
loop, usually with a BitmapOr of index scans on the inner side that is run
again for every outer row. If it is a filter on two different tables
(a.f = 1 OR b.g = 2), BitmapOr cannot help either, since it only combines
indexes of one relation, and the OR ends up as a join filter. The
textbook case is a star schema with an OR over conditions on two
dimension tables.

This transformation is extremely useful and in my experience, queries
that can profit from it occur frequently. So +1 for the effort.

Where it is not considered:

- ORs that only reference one relation, the argument is that in this
case, surely a BitmapOr or anything else do the job.
- volatile functions in the jointree, security quals or function/subquery
  RTEs, since the arms are evaluated more than once
- FULL joins, TABLESAMPLE, FOR UPDATE/SHARE, CTEs, set operations,
  recursive queries, well anything other than SELECT ?
- partitioned tables, also inside subqueries. Child RTEs are created inside
  query_planner(), so after arms prune differently their range table
  indexes no longer match the original one, i didn't try to make it work
yet the solution here is maybe to refix pointers back to match root
PlannerInfo for each arm, but this felt too much, i wonder if its worth
it for the benefit it can get for partitioned tables.
- ORs in JOIN ... ON clauses. Only the top level WHERE quals are looked at
  for now.

The transformation is not always beneficial. Here's an example:

SELECT o.*
FROM orders o
JOIN customers c ON o.customer_id = c.id
WHERE o.status = 'returned' -- very selective: 1k rows
OR c.tier = 'standard'; -- very unselective: 900k of 1M customers

When one condition is very selective a NLJ on the table with the more
selective condition is actually pretty efficient.

Do you unconditionally apply the transformation, or do you have
heuristics to only do it if it likely pays off?

--
David Geier

#3David Geier
geidav.pg@gmail.com
In reply to: Ayoub Kazar (#1)
Re: [PROPOSAL] Expand OR clauses in joins to UNION ALL paths

On 07.10.26 13:02, Ayoub Kazar wrote:

Attached is a patch that lets the planner rewrite an OR clause that spans
several relations into a UNION ALL with one branch per arm, and use that
plan when it is estimated to be cheaper.

Background

OR clauses that mention more than one relation are awkward for the planner
today. If the OR is the join condition itself (a.x = b.y OR a.x = b.z), it
cannot be a hash or merge join clause, so the only choice left is a nested
loop, usually with a BitmapOr of index scans on the inner side that is run
again for every outer row. If it is a filter on two different tables
(a.f = 1 OR b.g = 2), BitmapOr cannot help either, since it only combines
indexes of one relation, and the OR ends up as a join filter. The
textbook case is a star schema with an OR over conditions on two
dimension tables.

This transformation is extremely useful and in my experience, queries
that can profit from it occur frequently. So +1 for the effort.

Where it is not considered:

- ORs that only reference one relation, the argument is that in this
case, surely a BitmapOr or anything else do the job.
- volatile functions in the jointree, security quals or function/subquery
  RTEs, since the arms are evaluated more than once
- FULL joins, TABLESAMPLE, FOR UPDATE/SHARE, CTEs, set operations,
  recursive queries, well anything other than SELECT ?
- partitioned tables, also inside subqueries. Child RTEs are created inside
  query_planner(), so after arms prune differently their range table
  indexes no longer match the original one, i didn't try to make it work
yet the solution here is maybe to refix pointers back to match root
PlannerInfo for each arm, but this felt too much, i wonder if its worth
it for the benefit it can get for partitioned tables.
- ORs in JOIN ... ON clauses. Only the top level WHERE quals are looked at
  for now.

The transformation is not always beneficial. Here's an example:

SELECT o.*
FROM orders o
JOIN customers c ON o.customer_id = c.id
WHERE o.status = 'returned' -- very selective: 1k rows
OR c.tier = 'standard'; -- very unselective: 900k of 1M customers

When one condition is very selective a NLJ on the table with the more
selective condition is actually pretty efficient.

Do you unconditionally apply the transformation, or do you have
heuristics to only do it if it likely pays off?

--
David Geier

#4Ayoub Kazar
kazarayoub2004@gmail.com
In reply to: David Geier (#3)
Re: [PROPOSAL] Expand OR clauses in joins to UNION ALL paths

On 07/10/2026 17:42, David Geier wrote:

On 07.10.26 13:02, Ayoub Kazar wrote:

Attached is a patch that lets the planner rewrite an OR clause that spans
several relations into a UNION ALL with one branch per arm, and use that
plan when it is estimated to be cheaper.

Background

OR clauses that mention more than one relation are awkward for the planner
today. If the OR is the join condition itself (a.x = b.y OR a.x = b.z), it
cannot be a hash or merge join clause, so the only choice left is a nested
loop, usually with a BitmapOr of index scans on the inner side that is run
again for every outer row. If it is a filter on two different tables
(a.f = 1 OR b.g = 2), BitmapOr cannot help either, since it only combines
indexes of one relation, and the OR ends up as a join filter. The
textbook case is a star schema with an OR over conditions on two
dimension tables.

This transformation is extremely useful and in my experience, queries
that can profit from it occur frequently. So +1 for the effort.

Glad to hear.

Where it is not considered:

- ORs that only reference one relation, the argument is that in this
case, surely a BitmapOr or anything else do the job.
- volatile functions in the jointree, security quals or function/subquery
  RTEs, since the arms are evaluated more than once
- FULL joins, TABLESAMPLE, FOR UPDATE/SHARE, CTEs, set operations,
  recursive queries, well anything other than SELECT ?
- partitioned tables, also inside subqueries. Child RTEs are created inside
  query_planner(), so after arms prune differently their range table
  indexes no longer match the original one, i didn't try to make it work
yet the solution here is maybe to refix pointers back to match root
PlannerInfo for each arm, but this felt too much, i wonder if its worth
it for the benefit it can get for partitioned tables.
- ORs in JOIN ... ON clauses. Only the top level WHERE quals are looked at
  for now.

The transformation is not always beneficial. Here's an example:

SELECT o.*
FROM orders o
JOIN customers c ON o.customer_id = c.id
WHERE o.status = 'returned' -- very selective: 1k rows
OR c.tier = 'standard'; -- very unselective: 900k of 1M customers

When one condition is very selective a NLJ on the table with the more
selective condition is actually pretty efficient.

Do you unconditionally apply the transformation, or do you have
heuristics to only do it if it likely pays off?

No everything is planned like any other path, each arm in the OR gets
fully planned alone, then UNIONed ALL together, cost is recalculated on
this new Append path, so its cost based, not a rule.

Regards,
Ayoub Kazar

#5Zsolt Parragi
zsolt.parragi@percona.com
In reply to: Ayoub Kazar (#4)
Re: [PROPOSAL] Expand OR clauses in joins to UNION ALL paths

Hello!

I see the motivation / idea behind it, but I think this needs some more thought.

The patch seems to cause some test failures in the test suite (test_misc/003_check_guc, test_plan_advice/001_replan_regress.

And some quick testing revealed two more specific issues:

1. Shouldn't the patch either handle subplans, or skip queries containing them?

CREATE TABLE t1 (id int PRIMARY KEY, a int, c int);
CREATE TABLE t2 (id int PRIMARY KEY, b int);
INSERT INTO t1 SELECT g, g % 10, g % 7 FROM generate_series(1, 2000) g;
INSERT INTO t2 SELECT g, g % 10 FROM generate_series(1, 2000) g;
CREATE INDEX ON t2 (b);
ANALYZE t1, t2;
CREATE SEQUENCE flip_seq;
CREATE FUNCTION flip() RETURNS bool VOLATILE LANGUAGE sql
AS $$ SELECT nextval('flip_seq') % 3 = 0 $$;
SELECT count(*) FROM t1, t2
WHERE (SELECT flip() WHERE t1.id > 0) OR t1.a = t2.b;

2.

The default of 8 is a nice guess because i found that starting from 7 arms,
planning time sometimes doubles (in complicated queries).

The planning time and memory use seems to be exponential with nesting, this explain takes 153 seconds for me in a debug build:

create table t1 (id int primary key, a int, c int);
create table t2 (id int primary key, b int);
insert into t1 select g, g % 10, g % 7 from generate_series(1, 2000) g;
insert into t2 select g, g % 10 from generate_series(1, 2000) g;
analyze t1, t2;
explain (summary, memory, costs off, timing off) select x.id, max(s.b) as b from t1 x, (select x.id, max(s.b) as b from t1 x, (select x.id, max(s.b) as b from t1 x, (select x.id, max(s.b) as b from t1 x, (select x.id, max(s.b) as b from t1 x, (select x.id, max(s.b) as b from t1 x, (select x.id, max(s.b) as b from t1 x, (select id, b from t2) s where x.a = s.b or x.c = s.id or x.id = s.b group by x.id) s where x.a = s.b or x.c = s.id or x.id = s.b group by x.id) s where x.a = s.b or x.c = s.id or x.id = s.b group by x.id) s where x.a = s.b or x.c = s.id or x.id = s.b group by x.id) s where x.a = s.b or x.c = s.id or x.id = s.b group by x.id) s where x.a = s.b or x.c = s.id or x.id = s.b group by x.id) s where x.a = s.b or x.c = s.id or x.id = s.b group by x.id;

#6Ayoub Kazar
kazarayoub2004@gmail.com
In reply to: Zsolt Parragi (#5)
Re: [PROPOSAL] Expand OR clauses in joins to UNION ALL paths

Hello,

On 07/10/2026 23:44, Zsolt Parragi wrote:

Hello!

I see the motivation / idea behind it, but I think this needs some more thought.

Thanks for the review!

The patch seems to cause some test failures in the test suite
(test_misc/003_check_guc, test_plan_advice/001_replan_regress.

I was aware of GUC test, i forgot about that, so its fixed now.

For the plan_advice test, there's a join test where previously planner
was doing ScalarArrayOpExpr transformation, when i added or expansion it
became cheaper for that test case. IIUC pg_plan_advice doesn't support
having different join strategies across Append arms for the same
relation pair, i'm not sure how should i avoid this test fail without
doing something wrong like disabling or expansion before the join test ?

I suppose this might be a pg_plan_advice issue ?

And some quick testing revealed two more specific issues:

1. Shouldn't the patch either handle subplans, or skip queries containing them?

CREATE TABLE t1 (id int PRIMARY KEY, a int, c int);
CREATE TABLE t2 (id int PRIMARY KEY, b int);
INSERT INTO t1 SELECT g, g % 10, g % 7 FROM generate_series(1, 2000) g;
INSERT INTO t2 SELECT g, g % 10 FROM generate_series(1, 2000) g;
CREATE INDEX ON t2 (b);
ANALYZE t1, t2;
CREATE SEQUENCE flip_seq;
CREATE FUNCTION flip() RETURNS bool VOLATILE LANGUAGE sql
AS $$ SELECT nextval('flip_seq') % 3 = 0 $$;
SELECT count(*) FROM t1, t2
WHERE (SELECT flip() WHERE t1.id > 0) OR t1.a = t2.b;

Correct:
+ if (contain_subplans((Node *) parse->jointree->quals))
this should be enough i think.

2.

The default of 8 is a nice guess because i found that starting from 7 arms,
planning time sometimes doubles (in complicated queries).

The planning time and memory use seems to be exponential with nesting,
this explain takes 153 seconds for me in a debug build:

create table t1 (id int primary key, a int, c int);
create table t2 (id int primary key, b int);
insert into t1 select g, g % 10, g % 7 from generate_series(1, 2000) g;
insert into t2 select g, g % 10 from generate_series(1, 2000) g;
analyze t1, t2;
explain (summary, memory, costs off, timing off) select x.id, max(s.b)
as b from t1 x, (select x.id, max(s.b) as b from t1 x, (select x.id,
max(s.b) as b from t1 x, (select x.id, max(s.b) as b from t1 x,
(select x.id, max(s.b) as b from t1 x, (select x.id, max(s.b) as b
from t1 x, (select x.id, max(s.b) as b from t1 x, (select id, b from
t2) s where x.a = s.b or x.c = s.id or x.id = s.b group by x.id) s
where x.a = s.b or x.c = s.id or x.id = s.b group by x.id) s where x.a
= s.b or x.c = s.id or x.id = s.b group by x.id) s where x.a = s.b or
x.c = s.id or x.id = s.b group by x.id) s where x.a = s.b or x.c =
s.id or x.id = s.b group by x.id) s where x.a = s.b or x.c = s.id or
x.id = s.b group by x.id) s where x.a = s.b or x.c = s.id or x.id =
s.b group by x.id;

True, this shouldn't be allowed for subqueries IMO.

+ /* + * Only top-level queries may be expanded. Expanding within
subqueries + * leads to extreme planning overhead with nested
subqueries. + */ + if (root->parent_root != NULL) + return false;

I also found two other issues:

- Previously i had a comment on whether LateralRTEs should be allowed, i
found that they are not safe for this transformation, therefore there's
a new guard for it too.

- Derived tables with un-grouped aggregates can be optimized into
MinMaxAggPath nodes whose InitPlan replacement parameters are populated
in that arm's private subroot->minmax_aggs during plan creation. Because
set_subqueryscan_references() resolves the subquery's planner state
through the top-level root->simple_rel_array, this mapping is missing
during reference fixing, causing an Aggref found in non-Agg plan node
executor error.

Example:
SELECT * FROM agg_t1 t1, agg_t2 t2, (SELECT min(x) as mx FROM agg_t2) s
WHERE (t1.a = t2.x OR t1.b = t2.y) AND s.mx = 1;

so i added a guard for this too. (attached as v2 of the patch)

I'm not sure whether it is worth making some of the guarded cases work
with or-expansion, if the list doesn't grow bigger than this, i think
that not considering them would be cheaper.

Or we can do the inverse: the query is safe for expansion only if all
RTEs are base relations, not even inherited and partitioned relations.
The latter might be too restrictive but far simpler, maybe (attached as
v3 of the patch).

Thoughts ?

Regards,
Ayoub Kazar

Attachments:

t254090_6
v2-0001-Expand-OR-clauses-in-joins-to-UNION-ALL-Append-paths.patchtext/x-patch; charset=UTF-8; name=v2-0001-Expand-OR-clauses-in-joins-to-UNION-ALL-Append-paths.patchDownload+1012-6
v3-0001-Expand-OR-clauses-in-joins-to-UNION-ALL-Append-paths.patchtext/x-patch; charset=UTF-8; name=v3-0001-Expand-OR-clauses-in-joins-to-UNION-ALL-Append-paths.patchDownload+956-6
#7David Geier
geidav.pg@gmail.com
In reply to: Ayoub Kazar (#4)
Re: [PROPOSAL] Expand OR clauses in joins to UNION ALL paths

The transformation is not always beneficial. Here's an example:

SELECT o.*
FROM orders o
JOIN customers c ON o.customer_id = c.id
WHERE    o.status = 'returned' -- very selective: 1k rows
       OR c.tier = 'standard';  -- very unselective: 900k of 1M customers

When one condition is very selective a NLJ on the table with the more
selective condition is actually pretty efficient.

Do you unconditionally apply the transformation, or do you have
heuristics to only do it if it likely pays off?

No everything is planned like any other path, each arm in the OR gets
fully planned alone, then UNIONed ALL together, cost is recalculated on
this new Append path, so its cost based, not a rule.

Ah, that's cool!

I was thinking about it like a rewrite happening post-parsing /
pre-planning.

--
David Geier

#8Ayoub Kazar
kazarayoub2004@gmail.com
In reply to: Ayoub Kazar (#6)
Re: [PROPOSAL] Expand OR clauses in joins to UNION ALL paths

Rebased v2 and v3.

Regards,
Ayoub Kazar

Attachments:

t254090_8
v3-0001-Expand-OR-clauses-in-joins-to-UNION-ALL-Append-paths.patchtext/x-patch; charset=UTF-8; name=v3-0001-Expand-OR-clauses-in-joins-to-UNION-ALL-Append-paths.patchDownload+956-6
v2-0001-Expand-OR-clauses-in-joins-to-UNION-ALL-Append-paths.patchtext/x-patch; charset=UTF-8; name=v2-0001-Expand-OR-clauses-in-joins-to-UNION-ALL-Append-paths.patchDownload+1012-6
#9Zsolt Parragi
zsolt.parragi@percona.com
In reply to: Ayoub Kazar (#8)
Re: [PROPOSAL] Expand OR clauses in joins to UNION ALL paths
+		/* Only plain base relations are permitted */
+		if (rte->rtekind != RTE_RELATION)
+			return false;

This will even reject simple GROUP BY (RTE_GROUP)

SELECT a.x FROM a JOIN b ... WHERE a.f=1 OR b.g=2 GROUP BY a.x

And there are probably many other interesting query features the patch could support without problems.

I also want to point out that this can result in queries that otherwise work on master erroring out with the patch:

CREATE TABLE item (id int PRIMARY KEY, kind text);
CREATE TABLE attr (item_id int, val text, tag int);
INSERT INTO item
SELECT g, CASE WHEN g % 100 = 0 THEN 'txt' ELSE 'num' END
FROM generate_series(1, 100000) g;
INSERT INTO attr
SELECT g, CASE WHEN g % 100 = 0 THEN 'abc' ELSE (g % 500)::text END,
CASE WHEN g % 100 = 0 THEN 7 ELSE g % 1000 END
FROM generate_series(1, 100000) g;
CREATE INDEX ON item (kind);
CREATE INDEX ON attr (tag);
ANALYZE item, attr;

SELECT count(*) FROM item i JOIN attr a ON a.item_id = i.id
WHERE i.kind = 'txt' OR (a.val::int = 7 AND a.tag = 7);

Every 'txt' item in this database fails the right side of the OR, but because the left side is true, the right side is never evaluated.
The evaluation order isn't guaranteed in this case, the documentation explicitly tells people not to do this. So in that sense, breaking it isn't wrong, but it is still a noticeable behavior change.

#10Ayoub Kazar
kazarayoub2004@gmail.com
In reply to: Zsolt Parragi (#9)
Re: [PROPOSAL] Expand OR clauses in joins to UNION ALL paths

Hello again,

On 13/10/2026 00:13, Zsolt Parragi wrote:

+		/* Only plain base relations are permitted */
+		if (rte->rtekind != RTE_RELATION)
+			return false;

This will even reject simple GROUP BY (RTE_GROUP)

SELECT a.x FROM a JOIN b ... WHERE a.f=1 OR b.g=2 GROUP BY a.x

And there are probably many other interesting query features the patch
could support without problems.

Indeed, so this takes us to v4 which has guards that allow more cases:

+ /*
+ * Check RTEs. We allow only known to be safe RTE cases: - RTE_RELATION:
+ * plain base tables (not partitioned, no inheritance, no tablesample, not
+ * foreign) - RTE_JOIN: joins (except FULL joins) - RTE_VALUES:
+ * non-volatile values lists without subplans - RTE_FUNCTION: non-volatile
+ * function RTEs without subplans - RTE_TABLEFUNC: non-volatile table
+ * functions without subplans - RTE_SUBQUERY: only flattened/inert
+ * subqueries (subquery == NULL) - RTE_GROUP, RTE_RESULT: synthetic
+ * planner entries Any other or active RTE kind (e.g. active RTE_SUBQUERY,
+ * RTE_CTE) is rejected for safety.
+ */

These are the cases that i found safe to support without any extra effort.

Previously there were failing tests related to pg_plan_advice, because
since we generate the paths directly without a boundary between it and
outer query, pg_plan_advice can't make a difference between every
occurrence of a relation, therefore generating conflicting advice
Example:

Consider a query where each expanded arm prefers a different scan or
join strategy:
SELECT a.id, b.val FROM a JOIN b ON a.id = b.x
WHERE a.val = 10 OR b.val = 300;

In v4, arm paths were placed directly under Append without any relation
boundary.
Because both arms operated in the top-level query scope, pg_plan_advice
could not
differentiate table occurrences between Arm 1 and Arm 2, generating
conflicting
advice for the exact same relation aliases:

-- v4: Ambiguous/conflicting advice emitted for the same relation:
Generated Plan Advice:
JOIN_ORDER(a b)
JOIN_ORDER(b a) -- CONFLICT: Arm 1 joins (a b), Arm 2 joins (b a)
NESTED_LOOP_PLAIN(b a) -- CONFLICT: Arm 1 loops on b, Arm 2 loops on a
SEQ_SCAN(b) -- CONFLICT: Arm 2 wants Seq Scan on b...
INDEX_SCAN(a public.orexp_a_val b public.orexp_b_x a public.orexp_a_pkey)
PARTITIONWISE((a b))
NO_GATHER(a b)

When this advice was fed back into the planner, pg_plan_advice could not
tell which
arm each hint targeted, breaking its round-trip plan stability guarantee
and causing
test failures.

Solution in v5:
In v5, each arm is given its own PlannerInfo with a distinct plan_name
and wrapped in a synthetic
SubqueryScanPath pointing to an RTE_SUBQUERY.
Now its more closer to what would an equivalent SQL query be, a lesser
non-standard way to do it.

This allows pg_plan_advice to qualify relation identifiers per arm:

-- v5: Disambiguated per-arm relation identifiers:

JOIN_ORDER(a@orexpand b@orexpand)
JOIN_ORDER(b@orexpand_1 a@orexpand_1)
NESTED_LOOP_PLAIN(b@orexpand a@orexpand_1)
SEQ_SCAN(b@orexpand_1)
INDEX_SCAN(a@orexpand public.orexp_a_val b@orexpand public.orexp_b_x
a@orexpand_1 public.orexp_a_pkey)
PARTITIONWISE((a b))
NO_GATHER(a b orexpand orexpand_1 a@orexpand b@orexpand a@orexpand_1
b@orexpand_1)

Though, currently pg_plan_advice still thinks this is a PARTITIONWISE,
so i think there must be some things that should be done to
pg_plan_advice itself, to add more considerations of what actually can
be an Append over base relations.
This is the reason for v5, i concluded from a quick talk with Robert at
PGConf.EU that maybe it is half of the problem of v4 doing a
non-standard transformation without subqueries (AFAIK, there's no other
part of planner that does a change like this direct) and pg_plan_advice
assumptions (which are fair, CC'ed Robert for this).

Parallel query for this is also an opportunity to not miss, which i'll
do in a later state of the patch.

I also want to point out that this can result in queries that
otherwise work on master erroring out with the patch:

CREATE TABLE item (id int PRIMARY KEY, kind text);
CREATE TABLE attr (item_id int, val text, tag int);
INSERT INTO item
SELECT g, CASE WHEN g % 100 = 0 THEN 'txt' ELSE 'num' END
FROM generate_series(1, 100000) g;
INSERT INTO attr
SELECT g, CASE WHEN g % 100 = 0 THEN 'abc' ELSE (g % 500)::text END,
CASE WHEN g % 100 = 0 THEN 7 ELSE g % 1000 END
FROM generate_series(1, 100000) g;
CREATE INDEX ON item (kind);
CREATE INDEX ON attr (tag);
ANALYZE item, attr;

SELECT count(*) FROM item i JOIN attr a ON a.item_id = i.id
WHERE i.kind = 'txt' OR (a.val::int = 7 AND a.tag = 7);

Every 'txt' item in this database fails the right side of the OR, but
because the left side is true, the right side is never evaluated.
The evaluation order isn't guaranteed in this case, the documentation
explicitly tells people not to do this. So in that sense, breaking it
isn't wrong, but it is still a noticeable behavior change.

Nice catch, noted to be discussed later.

Regards,
Ayoub

Attachments:

t254090_10
v4-0001-Expand-OR-clauses-in-joins-to-UNION-ALL-Append-paths.patchtext/x-patch; charset=UTF-8; name=v4-0001-Expand-OR-clauses-in-joins-to-UNION-ALL-Append-paths.patchDownload+2245-2
v5-0001-Expand-OR-clauses-in-joins-to-UNION-ALL-Append-paths.patchtext/x-patch; charset=UTF-8; name=v5-0001-Expand-OR-clauses-in-joins-to-UNION-ALL-Append-paths.patchDownload+2273-2
#11Zsolt Parragi
zsolt.parragi@percona.com
In reply to: Ayoub Kazar (#10)
Re: [PROPOSAL] Expand OR clauses in joins to UNION ALL paths

Hello!

v5 fails the basic test suite for me in an assert enabled build

#12Ayoub Kazar
kazarayoub2004@gmail.com
In reply to: Zsolt Parragi (#11)
Re: [PROPOSAL] Expand OR clauses in joins to UNION ALL paths

On 27/10/2026 23:30, Zsolt Parragi wrote:

Hello! v5 fails the basic test suite for me in an assert enabled build

Apologies, i had inadvertently run the previous test cycle on a build
without asserts and all TAP tests.

The assertion failure tripped at:

TRAP: failed Assert("list_length(dest_tlist) ==
list_length(src_tlist)"), File: "tlist.c", Line: 332
This occurred in queries with upper operations (aggregates, COUNT(*), or
GROUP BY) atop an OR-expanded join. while or_expansion_align_path()
projected the subpath to match the joinrel's targetlist,
arm->subroot->processed_tlist still retained the upper query's
targetlist. so the mismatch between the subplan's targetlist and
subroot->processed_tlist triggered the assert.

The fix for v5 is  just to synchronize the subroot's targetlist right
after alignment:

+   /* Synchronize subroot tlist with the arm's actual output target */
+   arm->subroot->processed_tlist =
+  arm->subroot->parse->targetList =
+  make_tlist_from_pathtarget(aligned->pathtarget);
With this fix in place, all assertion checks pass. I have attached a 
fixed v5.

Later i found something else with pg_plan_advice story ; so v5 still
fails in one test here:

In v5, create_append_path() passed joinrel as the parent. Consequently,
Append.apprelids contained the join's base relations (e.g., {a, b} or
{generate_series, b}). This caused two problems for plan inspection:

So this is the reason we see Partitionwise, if the transformation was
doing something clean like an upper UNION ALL query with subqueries as
relids, it would have the same rtekind for each branch and would be a
normal Append from pg_plan_advice's perspective.
E.g: joining a table with a function scan or VALUES (e.g.,
generate_series(1, 4) g, table b WHERE g = b.x OR g = b.y),
pg_plan_advice threw:
ERROR: rtekind mismatch: 3 vs. 0

And as mentioned, an equivalent manual UNION ALL query does not suffer
from this, because a manual UNION ALL Append has an apprelids consisting
of just subquery RTIs (RTE_SUBQUERY).

So i thought of doing Set-Operation for AppendPath.

Instead of creating the AppendPath with joinrel as its parent, we build
it on an UPPERREL_SETOP upper relation keyed by the candidate arm
subqueries' RTIs, and then add it to joinrel->pathlist:

Now i'm not sure whether this is fine to do or not, especially given
that this kind of transformations has never been done in any other place
and this comes at an intermediate state of planning. At this point any
issue with pg_plan_advice is gone, because the patch has a more
standard-ish planning state than before.

what do you think ?

Regards,
Ayoub

Attachments:

t254090_12
v5-0001-Expand-OR-clauses-in-joins-to-UNION-ALL-Append-paths.patchtext/x-patch; charset=UTF-8; name=v5-0001-Expand-OR-clauses-in-joins-to-UNION-ALL-Append-paths.patchDownload+2276-2
v6-0001-Expand-OR-clauses-in-joins-to-UNION-ALL-Append-paths.patchtext/x-patch; charset=UTF-8; name=v6-0001-Expand-OR-clauses-in-joins-to-UNION-ALL-Append-paths.patchDownload+2296-2
#13Ayoub Kazar
kazarayoub2004@gmail.com
In reply to: Ayoub Kazar (#12)
Re: [PROPOSAL] Expand OR clauses in joins to UNION ALL paths

On 28/10/2026 02:32, Ayoub Kazar wrote:

On 27/10/2026 23:30, Zsolt Parragi wrote:

Hello! v5 fails the basic test suite for me in an assert enabled build

Apologies, i had inadvertently run the previous test cycle on a build
without asserts and all TAP tests.

The assertion failure tripped at:

TRAP: failed Assert("list_length(dest_tlist) ==
list_length(src_tlist)"), File: "tlist.c", Line: 332
This occurred in queries with upper operations (aggregates, COUNT(*),
or GROUP BY) atop an OR-expanded join. while or_expansion_align_path()
projected the subpath to match the joinrel's targetlist,
arm->subroot->processed_tlist still retained the upper query's
targetlist. so the mismatch between the subplan's targetlist and
subroot->processed_tlist triggered the assert.

The fix for v5 is  just to synchronize the subroot's targetlist right
after alignment:

+   /* Synchronize subroot tlist with the arm's actual output target */
+   arm->subroot->processed_tlist =
+  arm->subroot->parse->targetList =
+  make_tlist_from_pathtarget(aligned->pathtarget);
With this fix in place, all assertion checks pass. I have attached a 
fixed v5.

Later i found something else with pg_plan_advice story ; so v5 still
fails in one test here:

In v5, create_append_path() passed joinrel as the parent.
Consequently, Append.apprelids contained the join's base relations
(e.g., {a, b} or {generate_series, b}). This caused two problems for
plan inspection:

So this is the reason we see Partitionwise, if the transformation was
doing something clean like an upper UNION ALL query with subqueries as
relids, it would have the same rtekind for each branch and would be a
normal Append from pg_plan_advice's perspective.
E.g: joining a table with a function scan or VALUES (e.g.,
generate_series(1, 4) g, table b WHERE g = b.x OR g = b.y),
pg_plan_advice threw:
ERROR: rtekind mismatch: 3 vs. 0

And as mentioned, an equivalent manual UNION ALL query does not suffer
from this, because a manual UNION ALL Append has an apprelids
consisting of just subquery RTIs (RTE_SUBQUERY).

So i thought of doing Set-Operation for AppendPath.

Instead of creating the AppendPath with joinrel as its parent, we
build it on an UPPERREL_SETOP upper relation keyed by the candidate
arm subqueries' RTIs, and then add it to joinrel->pathlist:

Now i'm not sure whether this is fine to do or not, especially given
that this kind of transformations has never been done in any other
place and this comes at an intermediate state of planning. At this
point any issue with pg_plan_advice is gone, because the patch has a
more standard-ish planning state than before.

what do you think ?

Regards,
Ayoub

Here's a v6 (moving forward with this) with minor fixes, shouldn't fail
CI no more i think (had older gcc used without noticing).

Regards,
Ayoub

Attachments:

t254090_13
v6-0001-Expand-OR-clauses-in-joins-to-UNION-ALL-Append-paths.patchtext/x-patch; charset=UTF-8; name=v6-0001-Expand-OR-clauses-in-joins-to-UNION-ALL-Append-paths.patchDownload+3099-2
#14Robert Haas
robertmhaas@gmail.com
In reply to: Ayoub Kazar (#12)
Re: [PROPOSAL] Expand OR clauses in joins to UNION ALL paths

On Tue, Oct 27, 2026 at 9:33 PM Ayoub Kazar <ayoub.kazar@data-bene.io> wrote:

Now i'm not sure whether this is fine to do or not, especially given
that this kind of transformations has never been done in any other place
and this comes at an intermediate state of planning. At this point any
issue with pg_plan_advice is gone, because the patch has a more
standard-ish planning state than before.

what do you think ?

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.

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.

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. It's worth asking whether there's
some way to degrade gracefully rather than having a sharp edge.

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.

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.

--
Robert Haas
Databricks