Convert ALL SubLinks to ANY SubLinks

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

Convert ALL SubLinks to ANY SubLinks

От:
Richard Guo <guofenglinux@gmail.com>
Дата:
Вложения:
I was reading a paper on null-aware anti-joins (section 6 in [1]) and
noticed that they use <> ALL to represent NOT IN semantics.  We
currently execute ALL SubLinks using a nested-loop SubPlan.  This
made me realize that it could be beneficial to convert ALL SubLinks to
ANY SubLinks.

According to De Morgan's laws:

  foo op ALL (sub-SELECT) => NOT (foo negator_op ANY (sub-SELECT))
  NOT (foo op ALL (sub-SELECT)) => foo negator_op ANY (sub-SELECT)

This conversion makes it possible for the executor to evaluate the
sublink using a hashed SubPlan, which replaces a nested loop with a
more efficient hash probe.  Even better, because our planner already
knows how to pull up ANY SubLinks (and pending the other patch, NOT
ANY SubLinks), these transformed clauses have the chance to be
optimized directly into semijoins or anti-joins.

In the worst-case scenario where the transformed ANY sublink cannot be
pulled up and cannot be hashed, execution falls back to a nested-loop
SubPlan.  Performance in this scenario is effectively identical to the
legacy ALL SubPlan, so there should be no regressions.  Because the
operator is negated, the ANY subplan will short-circuit on the exact
same inner tuple that the ALL subplan would have short-circuited on.
The only added overhead is a single boolean NOT inversion per outer
tuple, which is, IMO, computationally negligible compared to the cost
of the nested-loop execution itself.

Attached is a draft patch illustrating the idea.  Any thoughts or
interest in this transformation?

[1] http://www.vldb.org/pvldb/vol2/vldb09-423.pdf

- Richard

Re: Convert ALL SubLinks to ANY SubLinks

От:
Andrei Lepikhov <lepihov@gmail.com>
Дата:
On 26/2/26 08:11, Richard Guo wrote:
> Attached is a draft patch illustrating the idea.  Any thoughts or
> interest in this transformation?
Thanks for sharing your thoughts.
I want to correct your statement on the 'no regression' phrase. In 
practice, users often report issues after each new sublink 
transformation goes live.

This happens because the transformation changes the 'join problem' 
order. Before, the subplan's join list was handled independently, but 
now its relations are mixed with those from higher levels. If the join 
collapse limit is exceeded, this can sometimes cause much worse 
performance than in earlier Postgres versions.

A recent example of this issue, where a query increased from 9 joins in 
PG14 to 18 joins in PG19, can be found in pgsql-performance [1].

[1] 
https://www.postgresql.org/message-id/flat/ECA94B5A-E5B4-45F7-B1B4-9BF754083164%40gmx.net

-- 
regards, Andrei Lepikhov,
pgEdge


Re: Convert ALL SubLinks to ANY SubLinks

От:
Richard Guo <guofenglinux@gmail.com>
Дата:
On Thu, Feb 26, 2026 at 8:37 PM Andrei Lepikhov  wrote:
> I want to correct your statement on the 'no regression' phrase. In
> practice, users often report issues after each new sublink
> transformation goes live.
>
> This happens because the transformation changes the 'join problem'
> order. Before, the subplan's join list was handled independently, but
> now its relations are mixed with those from higher levels. If the join
> collapse limit is exceeded, this can sometimes cause much worse
> performance than in earlier Postgres versions.

I'm not convinced this is a regression.  In scenarios where the join
tree becomes too large, wouldn't the standard solution be for the user
to tune join_collapse_limit (and maybe also geqo_threshold)?

If pulling up a subquery results in a suboptimal join order due to the
number of relations, the root cause lies in the limitations of the
join search algorithm itself.  It doesn't seem reasonable to penalize
the general subquery flattening mechanism for that limitation, and it
makes even less sense to fault this specific transformation, which
simply converts ALL_SUBLINK to ANY_SUBLINK so it can benefit from the
same hashed SubPlan and flattening mechanics that other subqueries
already enjoy.

- Richard


Re: Convert ALL SubLinks to ANY SubLinks

От:
wenhui qiu <qiuwenhuifx@gmail.com>
Дата:
HI 
> If pulling up a subquery results in a suboptimal join order due to the
> number of relations, the root cause lies in the limitations of the
> join search algorithm itself.  It doesn't seem reasonable to penalize
> the general subquery flattening mechanism for that limitation, and it
> makes even less sense to fault this specific transformation, which
> simply converts ALL_SUBLINK to ANY_SUBLINK so it can benefit from the
> same hashed SubPlan and flattening mechanics that other subqueries
>already enjoy.
Agree +1  


Thanks 


On Fri, Feb 27, 2026 at 9:42 AM Richard Guo <guofenglinux@gmail.com> wrote:
On Thu, Feb 26, 2026 at 8:37 PM Andrei Lepikhov <lepihov@gmail.com> wrote:
> I want to correct your statement on the 'no regression' phrase. In
> practice, users often report issues after each new sublink
> transformation goes live.
>
> This happens because the transformation changes the 'join problem'
> order. Before, the subplan's join list was handled independently, but
> now its relations are mixed with those from higher levels. If the join
> collapse limit is exceeded, this can sometimes cause much worse
> performance than in earlier Postgres versions.

I'm not convinced this is a regression.  In scenarios where the join
tree becomes too large, wouldn't the standard solution be for the user
to tune join_collapse_limit (and maybe also geqo_threshold)?

If pulling up a subquery results in a suboptimal join order due to the
number of relations, the root cause lies in the limitations of the
join search algorithm itself.  It doesn't seem reasonable to penalize
the general subquery flattening mechanism for that limitation, and it
makes even less sense to fault this specific transformation, which
simply converts ALL_SUBLINK to ANY_SUBLINK so it can benefit from the
same hashed SubPlan and flattening mechanics that other subqueries
already enjoy.

- Richard


Re: Convert ALL SubLinks to ANY SubLinks

От:
Andrei Lepikhov <lepihov@gmail.com>
Дата:
On 27/2/26 02:42, Richard Guo wrote:
> On Thu, Feb 26, 2026 at 8:37 PM Andrei Lepikhov  wrote:
>> I want to correct your statement on the 'no regression' phrase. In
>> practice, users often report issues after each new sublink
>> transformation goes live.
>>
>> This happens because the transformation changes the 'join problem'
>> order. Before, the subplan's join list was handled independently, but
>> now its relations are mixed with those from higher levels. If the join
>> collapse limit is exceeded, this can sometimes cause much worse
>> performance than in earlier Postgres versions.
> 
> I'm not convinced this is a regression.  In scenarios where the join
> tree becomes too large, wouldn't the standard solution be for the user
> to tune join_collapse_limit (and maybe also geqo_threshold)?

Depends on the exact definition of regression. In my mind, if a new 
Postgres version produces a worse plan by costs and execution times, and 
the list of possible solutions includes solely buying a more performant 
server (which is exactly what the join_collapse_limit increment means in 
a highly tuned production system) and rewriting the query, this is 
definitely a regression.

Also, do not forget the implicitly added LATERAL restriction. It is 
quite a simple puzzle to find a corner case that limits the search scope 
to less productive query plans.

I want to say I'm not against pull-up techniques as they are. I just 
point out that, according to (my personal) real-world statistics, 
correlated subquery pull-ups cause the most problematic user complaints, 
because we have almost no tools to help without changing the query 
generation driver.
It happens because of a Postgres planner limitation: any parse-tree 
transformation is 'blind' and irreversible. This issue happens more 
frequently when people try to use Postgres for kinda analytics tasks 
like 'monthly accountant report'. So, it may be beneficial to tangle 
extending pull-up techniques with work on how to ease corner cases.

-- 
regards, Andrei Lepikhov,
pgEdge


Re: Convert ALL SubLinks to ANY SubLinks

От:
Richard Guo <guofenglinux@gmail.com>
Дата:
Вложения:
On Thu, Feb 26, 2026 at 4:11 PM Richard Guo  wrote:
> Attached is a draft patch illustrating the idea.  Any thoughts or
> interest in this transformation?

Here is an updated version of the patch, with better comments and a
commit message.

Considering where we are in the current release cycle, I am targeting
this for v20.

- Richard

Re: Convert ALL SubLinks to ANY SubLinks

От:
solai v <solai.cdac@gmail.com>
Дата:
Вложения:
Hi all,



On Fri, Sep 11, 2026 at 11:57 AM Richard Guo  wrote:
>
> On Thu, Feb 26, 2026 at 4:11 PM Richard Guo  wrote:
> > Attached is a draft patch illustrating the idea.  Any thoughts or
> > interest in this transformation?
>
> Here is an updated version of the patch, with better comments and a
> commit message.
>
> Considering where we are in the current release cycle, I am targeting
> this for v20.


Thank you for the updated patch. I reviewed and tested the v2 patch.
Since the regression files in the patch were based on a slightly
different version of the tree, I manually integrated the new
regression test cases into subselect.sql and subselect.out. The
subselect regression tests passed successfully: # All 240 tests
passed. I also verified the new test cases added by the patch. The
plans matched the intent of the patch:

1. <> ALL is converted to NOT (ANY ...) and can use a hashed ANY SubPlan.
2. Row-wise <> ALL is similarly converted to a hashed ANY SubPlan.
3. Cases where hashing is not applicable fall back to an ANY SubPlan
with Materialize.
4. ALL cases that can be pulled up are converted into anti-joins.
5. Negated ALL cases can be pulled up into the corresponding join paths.
6. When the operator has no negator, the original ALL SubPlan is
retained as expected.

I also performed additional semantic testing against the equivalent De
Morgan transformation by comparing a < ALL (SELECT ...) with: NOT (a
>= ANY (SELECT ...)) using combinations involving ordinary values,
NULL values, empty subqueries, and NULL outer values. The results
matched in the cases tested, including the expected SQL
three-valued-logic behavior. In addition, I tested Boolean expressions
within the ALL test expression using both AND and OR expressions. The
resulting plans showed the expected conversion to NOT (ANY (...)),
while retaining the Boolean expression structure.
Overall, based on the code inspection, regression testing, plan
verification, and the additional semantic tests, I did not find any
correctness issues with the v2 patch. +1 from my side for v2 patch
based on the testing.

Regards,
Solai


Re: Convert ALL SubLinks to ANY SubLinks

От:
Rui Zhao <zhaorui126@gmail.com>
Дата:
Вложения:
Hi Richard,

Thanks for working on this optimization.

I found a valid custom operator class for which v2 turns a working
row-comparison ALL query into an error. Using the existing int4_tbl
regression table:

    CREATE OPERATOR #< (LEFTARG = integer, RIGHTARG = integer,
      FUNCTION = int4lt, NEGATOR = #>=);
    CREATE OPERATOR #>= (LEFTARG = integer, RIGHTARG = integer,
      FUNCTION = int4ge, NEGATOR = #<);
    CREATE OPERATOR CLASS regress_all_int_ops
      FOR TYPE integer USING btree AS
      OPERATOR 1 #<,
      OPERATOR 2 <=,
      OPERATOR 3 =,
      OPERATOR 4 >=,
      OPERATOR 5 >,
      FUNCTION 1 btint4cmp(integer, integer);

    SELECT f1 FROM int4_tbl
    WHERE (f1, f1) OPERATOR(#<) ALL
        (SELECT f1, f1 FROM int4_tbl WHERE f1 = 123456)
    ORDER BY f1;

Master returns -2147483647, -123456 and 0. On v2 I get:

    ERROR:  operator 16417 is not a member of opfamily 16419

NOT ALL fails too. The operator class passes amvalidate(). Its strategy
4 operator is the built-in >=, while the negator of #< is #>=. Both >=
and #>= call int4ge, but only >= belongs to this family.

negate_sublink_testexpr() replaces the operators with their negators
but keeps rcexpr->opfamilies. ExecInitExprRec() then calls
get_op_opfamily_properties() with #>= and the original family, which
causes the error.

The attached patch checks op_in_opfamily() before making that change.
If a negator is outside the original family, it leaves the ALL sublink
unchanged.

I also considered two other fixes:

1. Find a B-tree family containing the negator and update the
   corresponding entry in rcexpr->opfamilies.
2. Keep the original family and use get_opfamily_member() to find its
   operator for the opposite comparison. For example, when negating <,
   use the family's strategy 4 operator (>=).

In the built-in B-tree families and extensions I checked, including
citext, pgvector and pg_roaringbitmap, the negators were already in the
same family. So I think the attached small check is sufficient.

The patch includes regression tests for ALL and NOT ALL; both fail on
v2 and return the expected rows with the fix.

Regards,
Rui
FAQ