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

Поиск
Список
Период
Сортировка
Искать

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

От:
Ayoub Kazar <ayoub.kazar@data-bene.io>
Дата:
Вложения:
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]. An undirected edge becomes an OR over the two directions of the 
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], 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] 
https://www.postgresql.org/message-id/4ab664c3585d3c2da2d4c1d1bbed430e%40data-bene.io
[2] 
https://www.postgresql.org/message-id/flat/7f70bd5a-5d16-e05c-f0b4-2fdfc8873489%40BlueTreble.com

Regards,
Ayoub Kazar

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

От:
David Geier <geidav.pg@gmail.com>
Дата:
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


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

От:
David Geier <geidav.pg@gmail.com>
Дата:
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


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

От:
Ayoub Kazar <ayoub.kazar@data-bene.io>
Дата:
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


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

От:
Zsolt Parragi <zsolt.parragi@percona.com>
Дата:
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;


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

От:
Ayoub Kazar <ayoub.kazar@data-bene.io>
Дата:
Вложения:

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

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

От:
David Geier <geidav.pg@gmail.com>
Дата:
>> 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


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

От:
Ayoub Kazar <ayoub.kazar@data-bene.io>
Дата:
Вложения:
Rebased v2 and v3.

Regards,
Ayoub Kazar

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

От:
Zsolt Parragi <zsolt.parragi@percona.com>
Дата:
+		/* 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.


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

От:
Ayoub Kazar <ayoub.kazar@data-bene.io>
Дата:
Вложения:
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

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

От:
Zsolt Parragi <zsolt.parragi@percona.com>
Дата:
Hello!

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


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

От:
Ayoub Kazar <ayoub.kazar@data-bene.io>
Дата:
Вложения:
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

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

От:
Ayoub Kazar <ayoub.kazar@data-bene.io>
Дата:
Вложения:
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

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

От:
Robert Haas <robertmhaas@gmail.com>
Дата:
On Tue, Oct 27, 2026 at 9:33 PM Ayoub Kazar  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


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

От:
Ayoub Kazar <ayoub.kazar@data-bene.io>
Дата:
Вложения:
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
FAQ