Re: Exists pull-up application with JoinExpr
Re: Exists pull-up application with JoinExpr
Yes, you are right) Thank you for your interest to this thread)Hi Alena.Em ter., 24 de dez. de 2024 às 01:44, Alena Rybakina <a.rybakina@postgrespro.ru> escreveu:Hi, hackers!
I found one pull-up that works if the inner join condition is written through the where condition,
create temp table ta (id int primary key, val int); insert into ta values(1,1); insert into ta values(2,2);insert into ta values(3,3);create temp table tb (id int primary key, aval int); insert into tb values(4,1); insert into tb values(5,1); insert into tb values(1,2); create temp table tc (id int primary key, aid int); insert into tc values(6,1); insert into tc values(7,2);EXPLAIN (ANALYZE, COSTS OFF, SUMMARY OFF, TIMING OFF) SELECT * FROM ta WHERE EXISTS (SELECT * FROM tb, tc WHERE ta.id = tb.id);QUERY PLAN ------------------------------------------------------------------------- Nested Loop Semi Join (actual rows=1 loops=1) Buffers: local hit=6 -> Seq Scan on ta (actual rows=3 loops=1) Buffers: local hit=1 -> Nested Loop (actual rows=0 loops=3) Buffers: local hit=5 -> Index Only Scan using tb_pkey on tb (actual rows=0 loops=3) Index Cond: (id = ta.id) Heap Fetches: 1 Buffers: local hit=4 -> Seq Scan on tc (actual rows=1 loops=1) Buffers: local hit=1 Planning: Buffers: shared hit=67 read=12 (14 rows)but it doesn't work if it is written through the outside condition.
alena@postgres=# EXPLAIN (ANALYZE, COSTS OFF, SUMMARY OFF, TIMING OFF) SELECT * FROM ta WHERE EXISTS (SELECT * FROM tb JOIN tc ON ta.id = tb.id); QUERY PLAN ------------------------------------------------------ Seq Scan on ta (actual rows=1 loops=1) Filter: EXISTS(SubPlan 1) Rows Removed by Filter: 2 Buffers: local hit=5 SubPlan 1 -> Nested Loop (actual rows=0 loops=3) Buffers: local hit=4 -> Seq Scan on tb (actual rows=0 loops=3) Filter: (ta.id = id) Rows Removed by Filter: 3 Buffers: local hit=3 -> Seq Scan on tc (actual rows=1 loops=1) Buffers: local hit=1 Planning: Buffers: shared hit=16 read=9 (15 rows)
I have written a patch to add this functionality and now it gives an query plan:alena@postgres=# EXPLAIN (ANALYZE, COSTS OFF, SUMMARY OFF, TIMING OFF)
SELECT *
FROM ta
WHERE EXISTS (SELECT *
FROM tb JOIN tc
ON ta.id = tb.id);
QUERY PLAN
-------------------------------------------------------------------------
Nested Loop Semi Join (actual rows=1 loops=1)
Buffers: local hit=6
-> Seq Scan on ta (actual rows=3 loops=1)
Buffers: local hit=1
-> Nested Loop (actual rows=0 loops=3)
Buffers: local hit=5
-> Index Only Scan using tb_pkey on tb (actual rows=0 loops=3)
Index Cond: (id = ta.id)
Heap Fetches: 1
Buffers: local hit=4
-> Seq Scan on tc (actual rows=1 loops=1)
Buffers: local hit=1
(12 rows)tb and tc form a Cartesian product, but in the case of the intersection condition with tuples from the table ta (ta.id = tb.id). So, according to the join condition, tb intersects only with 1, and only it gets into the result, but at the same time they appear twice - this is because of the Cartesian product of tb with tc
How it works:I rewrote the code a bit so that it considers not only the quals in jointree->quals, but also those in join expression (subselect->jointree->fromlist). If they satisfy the conditions for using pull up, I add them to the list of clauses and form a "Bool" expression from them, joined by an "AND" operation.
I took a look at this patch and I did a little polishing on it.
And I believe that in testing, you need to set it to BUFFERS OFF,
because of the recent change made to ANALYZE.
The tests are failing, like this:QUERY PLAN
-------------------------------------------------------------------------
Nested Loop Semi Join (actual rows=2 loops=1)
+ Buffers: local hit=7
-> Seq Scan on ta (actual rows=2 loops=1)
+ Buffers: local hit=1
-> Nested Loop (actual rows=1 loops=2)
+ Buffers: local hit=6
-> Index Only Scan using tb_pkey on tb (actual rows=1 loops=2)
Index Cond: (id = ta.id)
Heap Fetches: 2
+ Buffers: local hit=4
-> Seq Scan on tc (actual rows=1 loops=2)
-(7 rows)
+ Buffers: local hit=2
+(12 rows)
-- Regards, Alena Rybakina Postgres Professional
Re: Exists pull-up application with JoinExpr
Hi Alena, Thank you for your work on subqueries with JOIN. Have you considered the scenario where in subquery includes a qual like (tc.aid = 1)? When I tried executing those queries I receive different results. In my opinion, to prevent this, we should add filters for such quals within the loop 'foreach (lc, all_clauses)' EXPLAIN (ANALYZE, COSTS OFF, SUMMARY OFF, TIMING OFF) SELECT * FROM ta WHERE EXISTS (SELECT * FROM tb, tc WHERE ta.id = tb.id AND tc.aid = 1); QUERY PLAN ---------------------------------------------------------------------- Hash Join (actual rows=1 loops=1) Hash Cond: (ta.id = tb.id) Buffers: local hit=3 -> Seq Scan on ta (actual rows=3 loops=1) Buffers: local hit=1 -> Hash (actual rows=3 loops=1) Buckets: 4096 Batches: 1 Memory Usage: 33kB Buffers: local hit=2 -> HashAggregate (actual rows=3 loops=1) Group Key: tb.id Batches: 1 Memory Usage: 121kB Buffers: local hit=2 -> Nested Loop (actual rows=3 loops=1) Buffers: local hit=2 -> Seq Scan on tb (actual rows=3 loops=1) Buffers: local hit=1 -> Materialize (actual rows=1 loops=3) Storage: Memory Maximum Storage: 17kB Buffers: local hit=1 -> Seq Scan on tc (actual rows=1 loops=1) Filter: (aid = 1) Rows Removed by Filter: 1 Buffers: local hit=1 (23 rows) ============================ EXPLAIN (ANALYZE, COSTS OFF, SUMMARY OFF, TIMING OFF) SELECT * FROM ta WHERE EXISTS (SELECT * FROM tb JOIN tc ON ta.id = tb.id WHERE tc.aid = 1); QUERY PLAN --------------------------------------------------------------------------- Seq Scan on ta (actual rows=1 loops=1) Filter: EXISTS(SubPlan 1) Rows Removed by Filter: 2 Buffers: local hit=6 SubPlan 1 -> Nested Loop (actual rows=0 loops=3) Buffers: local hit=5 -> Index Only Scan using tb_pkey on tb (actual rows=0 loops=3) Index Cond: (id = ta.id) Heap Fetches: 1 Buffers: local hit=4 -> Seq Scan on tc (actual rows=1 loops=1) Filter: (aid = 1) Buffers: local hit=1 (14 rows) -- Best regards, Ilia Evdokimov, Tantor Labs LLC.
Re: Exists pull-up application with JoinExpr
Hi! Thank you for your interest to this subject!
Hi Alena,
Thank you for your work on subqueries with JOIN.
Have you considered the scenario where in subquery includes a qual like (tc.aid = 1)? When I tried executing those queries I receive different results. In my opinion, to prevent this, we should add filters for such quals within the loop 'foreach (lc, all_clauses)'
EXPLAIN (ANALYZE, COSTS OFF, SUMMARY OFF, TIMING OFF) SELECT * FROM ta
WHERE EXISTS (SELECT * FROM tb, tc WHERE ta.id = tb.id AND tc.aid = 1);
QUERY PLAN
----------------------------------------------------------------------
Hash Join (actual rows=1 loops=1)
Hash Cond: (ta.id = tb.id)
Buffers: local hit=3
-> Seq Scan on ta (actual rows=3 loops=1)
Buffers: local hit=1
-> Hash (actual rows=3 loops=1)
Buckets: 4096 Batches: 1 Memory Usage: 33kB
Buffers: local hit=2
-> HashAggregate (actual rows=3 loops=1)
Group Key: tb.id
Batches: 1 Memory Usage: 121kB
Buffers: local hit=2
-> Nested Loop (actual rows=3 loops=1)
Buffers: local hit=2
-> Seq Scan on tb (actual rows=3 loops=1)
Buffers: local hit=1
-> Materialize (actual rows=1 loops=3)
Storage: Memory Maximum Storage: 17kB
Buffers: local hit=1
-> Seq Scan on tc (actual rows=1 loops=1)
Filter: (aid = 1)
Rows Removed by Filter: 1
Buffers: local hit=1
(23 rows)
============================
EXPLAIN (ANALYZE, COSTS OFF, SUMMARY OFF, TIMING OFF)
SELECT * FROM ta WHERE EXISTS (SELECT * FROM tb JOIN tc ON ta.id =
tb.id WHERE tc.aid = 1);
QUERY PLAN
---------------------------------------------------------------------------
Seq Scan on ta (actual rows=1 loops=1)
Filter: EXISTS(SubPlan 1)
Rows Removed by Filter: 2
Buffers: local hit=6
SubPlan 1
-> Nested Loop (actual rows=0 loops=3)
Buffers: local hit=5
-> Index Only Scan using tb_pkey on tb (actual rows=0 loops=3)
Index Cond: (id = ta.id)
Heap Fetches: 1
Buffers: local hit=4
-> Seq Scan on tc (actual rows=1 loops=1)
Filter: (aid = 1)
Buffers: local hit=1
(14 rows)
You are right, at the moment the code is not processed if there is a constant qual in the subquery (like t1.x1=1 in the example below) and this problem is not only related to the current patch.
For example you can get such a query plan if you complete this request to the master:
create table t (x int); create table t1 (x1 int); create table t2 (x2 int); EXPLAIN (ANALYZE, COSTS OFF, SUMMARY OFF, TIMING OFF) SELECT 1 FROM t WHERE EXISTS (SELECT 1 FROM t1 where t1.x1 = 1); QUERY PLAN ------------------------------------------------ Result (actual rows=0 loops=1) One-Time Filter: (InitPlan 1).col1 InitPlan 1 -> Seq Scan on t1 (actual rows=0 loops=1) Filter: (x1 = 1) -> Seq Scan on t (never executed) (6 rows)
It's all because of the check in this function - this qual has levelsoup = 0, not 1 (see (!contain_vars_of_level(whereClause, 1)), but I already found out that by changing this, the logic of correction there is required a little more complicated. At the moment, I'm working to add this processing to the patch.
Thanks for the case!
-- Regards, Alena Rybakina Postgres Professional
Re: pull-up subquery if JOIN-ON contains refs to upper-query
On 10.02.2025 23:51, Ilia Evdokimov wrote: > > On 09.02.2025 18:14, Alena Rybakina wrote: >> Hi! I found another example where the transformation worked >> incorrectly and reconsidered the idea. >> >> As for conversion of exists_sublink_to_ANY, we need to get the >> flattened implicit-AND list of clauses and pull out the chunks of the >> WHERE clause that belong to the parent query, >> since we are called halfway through the parent's >> preprocess_expression() and earlier steps of preprocess_expression() >> wouldn't get applied to the pulled-up stuff unless we do them here. >> We also do some processing for vars depending on which side the var >> is on - if it's in a subquery, we only need to lower its level >> (varlevel) because subquery will be flatted, while >> for other vars that belong to the parent query, we need to do >> preparation to pull up the sub-select into top range table. >> >> For those expressions that we couldn't assign to either list, we >> define newWhere and apply both cases. >> > > When I run 'make -C contrib/ check', tests of postgres_fdw extension > failed. I might be wrong, but you should be careful with LIMIT. > Thank you for the review, I'm working on it. -- Regards, Alena Rybakina Postgres Professional
Re: pull-up subquery if JOIN-ON contains refs to upper-query
Hi!
My colleague reviewed my patch and gave feedback on how to improve it -
for some queries with data types that I did not consider, pull-up is not
applied, although it should. Some of them:
EXPLAIN (ANALYZE, COSTS OFF, SUMMARY OFF, TIMING OFF, BUFFERS OFF)
SELECT 1
FROM ta
WHERE EXISTS (SELECT 1
FROM tb
JOIN tc
ON ta.id = tb.id
AND tb.id = ANY('{1}'::int[])
);
QUERY PLAN
--------------------------------------------------------------------------
Seq Scan on ta (actual rows=1.00 loops=1)
Filter: EXISTS(SubPlan 1)
Rows Removed by Filter: 1
SubPlan 1
-> Nested Loop (actual rows=0.50 loops=2)
-> Seq Scan on tb (actual rows=0.50 loops=2)
Filter: ((id = ANY ('{1}'::integer[])) AND (ta.id = id))
Rows Removed by Filter: 2
-> Seq Scan on tc (actual rows=1.00 loops=1)
EXPLAIN (ANALYZE, COSTS OFF, SUMMARY OFF, TIMING OFF, BUFFERS OFF)
SELECT 1
FROM ta
WHERE EXISTS (SELECT 1
FROM tb
JOIN tc
ON ta.id = tb.id
AND tb.is_active
);
QUERY PLAN
---------------------------------------------------------
Seq Scan on ta (actual rows=2.00 loops=1)
Filter: EXISTS(SubPlan 1)
SubPlan 1
-> Nested Loop (actual rows=1.00 loops=2)
-> Seq Scan on tb (actual rows=1.00 loops=2)
Filter: (is_active AND (ta.id = id))
Rows Removed by Filter: 0
-> Seq Scan on tc (actual rows=1.00 loops=2)
EXPLAIN (ANALYZE, COSTS OFF, SUMMARY OFF, TIMING OFF, BUFFERS OFF)
SELECT 1
FROM ta
WHERE EXISTS (SELECT 1
FROM tb
JOIN tc
ON ta.id = tb.id
AND tb.is_active IS NOT NULL
);
QUERY PLAN
--------------------------------------------------------------------
Seq Scan on ta (actual rows=2.00 loops=1)
Filter: EXISTS(SubPlan 1)
SubPlan 1
-> Nested Loop (actual rows=1.00 loops=2)
-> Seq Scan on tb (actual rows=1.00 loops=2)
Filter: ((is_active IS NOT NULL) AND (ta.id = id))
Rows Removed by Filter: 0
-> Seq Scan on tc (actual rows=1.00 loops=2)
UPDATE tb SET is_active = NULL WHERE id = 2;
EXPLAIN (ANALYZE, COSTS OFF, SUMMARY OFF, TIMING OFF, BUFFERS OFF)
SELECT 1
FROM ta
WHERE EXISTS (SELECT 1
FROM tb
JOIN tc
ON ta.id = tb.id
AND tb.is_active IS NULL
);
QUERY PLAN
----------------------------------------------------------------
Seq Scan on ta (actual rows=1.00 loops=1)
Filter: EXISTS(SubPlan 1)
Rows Removed by Filter: 1
SubPlan 1
-> Nested Loop (actual rows=0.50 loops=2)
-> Seq Scan on tb (actual rows=0.50 loops=2)
Filter: ((is_active IS NULL) AND (ta.id = id))
Rows Removed by Filter: 4
-> Seq Scan on tc (actual rows=1.00 loops=1)
I see that I need to add a walker that, when traversing the tree,
determines whether there are conditions under which pull-up is
impossible - the presence of
volatility of functions and other restrictions, and leave the
transformation for the var objects that I added before, I described it
here.
Unfortunately, I need a few days to implement this and need time for a
review, and I think I will not have time to do this before the code
freeze, so
I am moving this to the next commitfest and not changing the status
"awaiting the author".
On 11.02.2025 18:59, Alena Rybakina wrote:
> On 10.02.2025 23:51, Ilia Evdokimov wrote:
>>
>> On 09.02.2025 18:14, Alena Rybakina wrote:
>>> Hi! I found another example where the transformation worked
>>> incorrectly and reconsidered the idea.
>>>
>>> As for conversion of exists_sublink_to_ANY, we need to get the
>>> flattened implicit-AND list of clauses and pull out the chunks of
>>> the WHERE clause that belong to the parent query,
>>> since we are called halfway through the parent's
>>> preprocess_expression() and earlier steps of preprocess_expression()
>>> wouldn't get applied to the pulled-up stuff unless we do them here.
>>> We also do some processing for vars depending on which side the var
>>> is on - if it's in a subquery, we only need to lower its level
>>> (varlevel) because subquery will be flatted, while
>>> for other vars that belong to the parent query, we need to do
>>> preparation to pull up the sub-select into top range table.
>>>
>>> For those expressions that we couldn't assign to either list, we
>>> define newWhere and apply both cases.
>>>
>>
>> When I run 'make -C contrib/ check', tests of postgres_fdw extension
>> failed. I might be wrong, but you should be careful with LIMIT.
>>
> Thank you for the review, I'm working on it.
>
Sorry for not responding, but I will fix this bug after I update the
code based on the comments above. Thank you for noticing and writing to
me, your feedback is very important.
--
Regards,
Alena Rybakina
Postgres Professional
Re: pull-up subquery if JOIN-ON contains refs to upper-query
On 02.04.2025 19:39, Alena Rybakina wrote: > > I see that I need to add a walker that, when traversing the tree, > determines whether there are conditions under which pull-up is > impossible - the presence of > volatility of functions and other restrictions, and leave the > transformation for the var objects that I added before, I described it > here. > I have some concerns about pulling up every clause from the subquery with one column. In particular, not every clause is safe or beneficial to pull up: OR-clauses, CASE expressions, nested sublinks could significantly change how the planner estimates the number of rows or applies filters, especially when they are not true join predicates. Pulling them up might lead to worse plans, or even change the semantics in subtle ways. I think before applying such transformations, we should make sure they are not only safe but actually improve the resulting plan.
Re: pull-up subquery if JOIN-ON contains refs to upper-query
Hi, all! I updated the patch and it looks nice. All the problems have been solved.
On 02.04.2025 19:39, Alena Rybakina wrote:
I see that I need to add a walker that, when traversing the tree, determines whether there are conditions under which pull-up is impossible - the presence of
volatility of functions and other restrictions, and leave the transformation for the var objects that I added before, I described it here.
I have some concerns about pulling up every clause from the subquery with one column. In particular, not every clause is safe or beneficial to pull up: OR-clauses, CASE expressions, nested sublinks could significantly change how the planner estimates the number of rows or applies filters, especially when they are not true join predicates. Pulling them up might lead to worse plans, or even change the semantics in subtle ways. I think before applying such transformations, we should make sure they are not only safe but actually improve the resulting plan.
There may indeed be cases where a query plan without pull-up is worse than with pull-up.
For example, as shown below, with pull-up we don't need to scan two tables and perform a join, since the subquery returns 0 rows (no matching tuples in the inner sequential scan in a parameterized Nested Loop).
However, this cannot be detected at the current planning stage - we simply don't have that information yet.
Do you have any ideas on how to solve this problem? So far, the only approach I see is to try an alternative plan but I'm still learning this.
For example:
create table t(x int);
create table t1(x int);
create table t2(x int);
insert into t2 select id from generate_series(20001,30000) as id;
insert into t1 select id from generate_series(10001,20000) as id;
insert into t select id from generate_series(1,10000) as id;
vacuum analyze;
explain analyze select * from t where exists (select * from t1 join t2 on t.x = t1.x);
with my patch:
QUERY PLAN
----------------------------------------------------------------------------------------------------------------------------------------
Hash Join (cost=1500540.00..1500822.50 rows=10000 width=4) (actual time=70694.658..70694.662 rows=0.00 loops=1)
Hash Cond: (t.x = t1.x)
Buffers: shared hit=135
-> Seq Scan on t (cost=0.00..145.00 rows=10000 width=4) (actual time=0.009..1.545 rows=10000.00 loops=1)
Buffers: shared hit=45
-> Hash (cost=1500415.00..1500415.00 rows=10000 width=4) (actual time=70690.524..70690.526 rows=10000.00 loops=1)
Buckets: 16384 Batches: 1 Memory Usage: 480kB
Buffers: shared hit=90
-> HashAggregate (cost=1500315.00..1500415.00 rows=10000 width=4) (actual time=70683.143..70686.590 rows=10000.00 loops=1)
Group Key: t1.x
Batches: 1 Memory Usage: 793kB
Buffers: shared hit=90
-> Nested Loop (cost=0.00..1250315.00 rows=100000000 width=4) (actual time=0.019..25650.447 rows=100000000.00 loops=1)
Buffers: shared hit=90
-> Seq Scan on t1 (cost=0.00..145.00 rows=10000 width=4) (actual time=0.006..4.931 rows=10000.00 loops=1)
Buffers: shared hit=45
-> Materialize (cost=0.00..195.00 rows=10000 width=0) (actual time=0.000..0.875 rows=10000.00 loops=10000)
Storage: Memory Maximum Storage: 519kB
Buffers: shared hit=45
-> Seq Scan on t2 (cost=0.00..145.00 rows=10000 width=0) (actual time=0.007..1.246 rows=10000.00 loops=1)
Buffers: shared hit=45
Planning:
Buffers: shared hit=36 read=3
Planning Time: 0.375 ms
Execution Time: 70695.154 ms
without my patch:
QUERY PLAN
---------------------------------------------------------------------------------------------------------------------------
Seq Scan on t (cost=0.00..309.30 rows=5738 width=4) (actual time=68268.562..68268.565 rows=0.00 loops=1)
Filter: EXISTS(SubPlan 1)
Rows Removed by Filter: 10000
Buffers: shared hit=900045
SubPlan 1
-> Nested Loop (cost=0.00..8524.27 rows=654075 width=0) (actual time=6.823..6.823 rows=0.00 loops=10000)
Buffers: shared hit=900000
-> Seq Scan on t2 (cost=0.00..159.75 rows=11475 width=0) (actual time=0.011..1.660 rows=10000.00 loops=10000)
Buffers: shared hit=450000
-> Materialize (cost=0.00..188.72 rows=57 width=0) (actual time=0.000..0.000 rows=0.00 loops=100000000)
Storage: Memory Maximum Storage: 17kB
Buffers: shared hit=450000
-> Seq Scan on t1 (cost=0.00..188.44 rows=57 width=0) (actual time=2.403..2.403 rows=0.00 loops=10000)
Filter: (t.x = x)
Rows Removed by Filter: 10000
Buffers: shared hit=450000
Planning:
Buffers: shared hit=40 read=16
Planning Time: 0.487 ms
Execution Time: 68268.600 ms
-- Regards, Alena Rybakina Postgres Professional
Re: pull-up subquery if JOIN-ON contains refs to upper-query
Hi Alena,
I tested the latest patch on current master and verified the planner
behavior for the EXISTS pull-up cases described in the thread.
Before applying the patch, the following query produced an EXISTS(SubPlan) plan:
EXPLAIN (ANALYZE, COSTS OFF, SUMMARY OFF, TIMING OFF)
SELECT *
FROM ta
WHERE EXISTS (
SELECT *
FROM tb
JOIN tc ON ta.id = tb.id
);
Plan before patch:
Seq Scan on ta
Filter: EXISTS(SubPlan exists_1)
After applying the patch, the same query is transformed into:
Nested Loop Semi Join
with Index Only Scan on tb_pkey, so the pull-up optimization is now
applied correctly for JOIN ON clauses referencing outer Vars.
I also tested some additional cases mentioned in the discussion:
1. NOT EXISTS case
planner generated Nested Loop Anti Join as expected.
2 . Constant qual case (WHERE tc.aid = 1)
planner produced an optimized Hash Join plan and avoided EXISTS(SubPlan).
3. ANY array condition
tb.id = ANY('{1}'::int[])
planner successfully used Index Only Scan and generated an
optimized join plan.
In all tested cases, query results remained correct and I did not
observe incorrect transformations during my testing.
Overall the patch behavior looks good from my side and the planner now
behaves consistently for these EXISTS pull-up scenarios.
Regards,
Solaimurugan V
Re: pull-up subquery if JOIN-ON contains refs to upper-query
Do you have any ideas on how to solve this problem? So far, the only approach I see is to try an alternative plan but I'm still learning this.
Hi,
I've reviewed this patch, and I have suggestion about the approach.
Currently, the patch extends 'convert_EXISTS_sublick_to_join' with quite complex logic (clause collection, volatile checks, rewriting join quals, etc). While it works, the amount of branching and special cases makes the function harder to follow.
Looking at the logic, it seems that a large part of the complexity comes from trying to directly adapt 'convert_EXISTS_sublink_to_join' instead of factoring out a dedicated path. An alternative would be to introduce a separate function 'convert_EXISTS_sublink_to_lateral_join' - with a similar API to 'convert_ANY_sublink_to_join'. Such a function can focus only on the EXISTS-to-join case, while keeping the existing function shorter and easier to reason about.
I even made some first rough sketches of this approach (not a finished patch, just an outline). Of course, it would still need proper adaptation, but I think it demonstrates that the overall structure can be kept simpler.
What do you think about refactoring in this direction?
--
Best regards,
Ilia Evdokimov,
Tantor Labs LLC,
https://tantorlabs.com
Re: pull-up subquery if JOIN-ON contains refs to upper-query
On 04.06.2025 13:40, Alena Rybakina wrote:Do you have any ideas on how to solve this problem? So far, the only approach I see is to try an alternative plan but I'm still learning this.
Hi,
I've reviewed this patch, and I have suggestion about the approach.
Currently, the patch extends 'convert_EXISTS_sublick_to_join' with quite complex logic (clause collection, volatile checks, rewriting join quals, etc). While it works, the amount of branching and special cases makes the function harder to follow.
Looking at the logic, it seems that a large part of the complexity comes from trying to directly adapt 'convert_EXISTS_sublink_to_join' instead of factoring out a dedicated path. An alternative would be to introduce a separate function 'convert_EXISTS_sublink_to_lateral_join' - with a similar API to 'convert_ANY_sublink_to_join'. Such a function can focus only on the EXISTS-to-join case, while keeping the existing function shorter and easier to reason about.
I even made some first rough sketches of this approach (not a finished patch, just an outline). Of course, it would still need proper adaptation, but I think it demonstrates that the overall structure can be kept simpler.
What do you think about refactoring in this direction?
--
Best regards,
Ilia Evdokimov,
Tantor Labs LLC,
https://tantorlabs.com
I'll look at this. I need some time to consider it.
I'm working on this approach right now. I introduced mutator and made the transformation if it is possible there but I need to fix some bugs.
Re: pull-up subquery if JOIN-ON contains refs to upper-query
Hi, I rebased the patch and fixed earlier problem. On 03.09.2025 00:20, Alena Rybakina wrote: > > I'll look at this. I need some time to consider it. > > I'm working on this approach right now. I introduced mutator and made > the transformation if it is possible there but I need to fix some bugs. >
Re: pull-up subquery if JOIN-ON contains refs to upper-query
Hi!
I think this approach isn’t fully correct. By forming a join between a subquery and the outer relation, you effectively force the optimizer to choose a Nested Loop join. Furthermore, it prevents the planner from exploring all join orders between the subquery’s tables and the outer relation, so we may miss a more optimal plan.Hi,
I've reviewed this patch, and I have suggestion about the approach.
Currently, the patch extends 'convert_EXISTS_sublick_to_join' with quite complex logic (clause collection, volatile checks, rewriting join quals, etc). While it works, the amount of branching and special cases makes the function harder to follow.
Looking at the logic, it seems that a large part of the complexity comes from trying to directly adapt 'convert_EXISTS_sublink_to_join' instead of factoring out a dedicated path. An alternative would be to introduce a separate function 'convert_EXISTS_sublink_to_lateral_join' - with a similar API to 'convert_ANY_sublink_to_join'. Such a function can focus only on the EXISTS-to-join case, while keeping the existing function shorter and easier to reason about.
I even made some first rough sketches of this approach (not a finished patch, just an outline). Of course, it would still need proper adaptation, but I think it demonstrates that the overall structure can be kept simpler.
What do you think about refactoring in this direction?
With your patch, I consistently get the following plan. I even disabled nested loops to see whether the planner could switch to a Hash Join or Merge Join, but those aren’t applicable with lateral parameters in this pattern.
CREATE TABLE ta (id int PRIMARY KEY, val int);
INSERT INTO ta VALUES (1,1), (2,2);
CREATE TABLE tb (id int PRIMARY KEY, aval int);
INSERT INTO tb VALUES (1,1), (2,1);
CREATE TABLE tc (id int PRIMARY KEY, aid int);
INSERT INTO tc VALUES (3,5), (1,5);
CREATE TABLE td (id int PRIMARY KEY, aid int);
INSERT INTO td VALUES (1,6), (2,7), (3,8), (4,9);
CREATE TABLE te (id int PRIMARY KEY, aid int);
INSERT INTO te VALUES (5,6), (6,7), (7,8), (4,9), (1,1);
SET enable_nestloop = OFF;
EXPLAIN ANALYZE
SELECT ta.id
FROM ta
WHERE EXISTS (
SELECT 1
FROM tb
WHERE tb.id = ta.id
AND EXISTS (SELECT 1 FROM tc WHERE tc.id = tb.id)
);
QUERY PLAN
--------------------------------------------------------------------------------------------------------------------------------
Nested Loop Semi Join (cost=0.31..37017.50 rows=2260 width=4) (actual time=0.116..0.142 rows=2.00 loops=1)
Disabled: true
Buffers: local hit=9
-> Seq Scan on ta (cost=0.00..32.60 rows=2260 width=4) (actual time=0.037..0.039 rows=2.00 loops=1)
Buffers: local hit=1
-> Nested Loop Semi Join (cost=0.31..16.36 rows=1 width=0) (actual time=0.045..0.046 rows=1.00 loops=2)
Disabled: true
Buffers: local hit=8
-> Index Only Scan using tb_pkey on tb (cost=0.15..8.17 rows=1 width=4) (actual time=0.030..0.030 rows=1.00 loops=2)
Index Cond: (id = ta.id)
Heap Fetches: 2
Index Searches: 2
Buffers: local hit=4
-> Index Only Scan using tc_pkey on tc (cost=0.15..8.17 rows=1 width=4) (actual time=0.010..0.010 rows=1.00 loops=2)
Index Cond: (id = ta.id)
Heap Fetches: 2
Index Searches: 2
Buffers: local hit=4
Planning Time: 0.539 ms
Execution Time: 0.252 ms
(20 rows)
Anyway, thank you for the work and attention here - your feedback was useful!
I’ve also rebased the patch on current master.
Re: pull-up subquery if JOIN-ON contains refs to upper-query
I have updated the patch with some bug-fixes after having run Smith's test with lateral and null elements. To detect lateral elements I left the check that there are no one outer references left in the subquery after the mutator transformation. Everything looks well now. I currently continue testing my patch to detect more corner-cases. Feel free to review my patch! ----------- Best regards, Yandex Cloud Alena Rybakina
Re: pull-up subquery if JOIN-ON contains refs to upper-query
Hi Peter, Thank you for the review, and sorry for the long delay. You were right. While checking your comments I found that v7 gives wrong results with outer joins, for example: create table o(x int, y int); insert into o values (1,1),(2,2),(3,3); create table a(x int, y int); insert into a values (1,10),(5,50); create table b(x int, y int); insert into b values (7,70); select * from o where exists (select 1 from a left join b on a.x = o.x); It should return all three rows, but v7 returns only one. So I rewrote the patch the way you suggested. v8 is attached. On Fri, May 8, 2026 at 8:45 PM Peter Petrov wrote: > We need to separate two things: the jointree and the WHERE clause, so > it's possible to do something like this > ... > if (contain_vars_of_level((Node *) subselect, 1)) > return NULL; Done, almost as you wrote. The jointree is taken out of the sub-select, and the rest of it must not refer to the parent query. Then the jointree is put back and checked by the new walker. > 2) We don't need to use get_relids_in_jointree() and nullable_above > ... > I fear that you don't check FULL JOINS here. Agreed, I was wrong about this in my last mail. The new code walks the jointree from the top down with an is_nullable_side flag, and handles FULL JOIN. A correlated qual is moved up only if it is in the ON clause of an inner join that is not on the nullable side of an outer join. Otherwise the sublink is not pulled up. > 3) ... I am not sure that the mutator is a good name here. Agreed. The mutator and HoistJoinQualsContext are gone. Now it is a simple walker that collects the joins whose quals should be moved. > 4) After checking the WHERE clause and the jointree we can traverse our > list, make a new whereClause by appending quals with outer references Done, with make_and_qual(). > 5) I have also noticed that you are using canonicalize_qual() Removed. > 6) I have noticed the new output from one regression test. That was a bug: the ON clauses of the left joins were replaced with "true". v8 doesn't change join.out. > 7) There is a SubLink which won't be pulled up Right, the subqueries in FROM are not flattened yet when pull_up_sublinks() runs, so the reference to A looks like a lateral reference. I agree with you that this is a separate change, so I'd like to leave it for later. Other changes: - Rebased on current master. - Removed the tests that didn't check anything new and added tests for outer joins, including the case above. - Rewrote the commit message. -- Regards, Alena Rybakina Yandex
Re: pull-up subquery if JOIN-ON contains refs to upper-query
Hi Alena, Thanks for v8. The walker is much easier to follow now, and all of Peter's points look addressed to me. I compared the results of random EXISTS/NOT EXISTS queries with and without the pull-up (adding OFFSET 0 to the sub-select blocks it). The queries had nested inner and outer joins in the sub-select, correlated and uncorrelated quals in the ON clauses, and NULLs in the data. About 13.5k queries ran, and about 1250 of them go through the new code path. I found no wrong results and no assertion failures, so the approach looks correct to me. My main comment is about the regression tests. A few things are missing in the regression tests: 1. anti join cases 2. query results not only EXPLAIN output 3. An EXISTS sublink in the ON clause of an outer join in the parent query, where the moved qual interacts with the available_rels check. -- Best regards, Ilia Evdokimov, Tantor Labs LLC, https://tantorlabs.com/
Re: pull-up subquery if JOIN-ON contains refs to upper-query
Hi! Thank you for the review! On 28.09.2026 18:56, Ilia Evdokimov wrote: > Hi Alena, > > Thanks for v8. The walker is much easier to follow now, and all of > Peter's points look addressed to me. > > I compared the results of random EXISTS/NOT EXISTS queries with and > without the pull-up (adding OFFSET 0 to the sub-select blocks it). The > queries had nested inner and outer joins in the sub-select, correlated > and uncorrelated quals in the ON clauses, and NULLs in the data. About > 13.5k queries ran, and about 1250 of them go through the new code > path. I found no wrong results and no assertion failures, so the > approach looks correct to me. Thank you for testing! I haven't found any issues either during Smith's test or in a one-hour SQLancer run. > > My main comment is about the regression tests. A few things are > missing in the regression tests: > > 1. anti join cases > 2. query results not only EXPLAIN output > 3. An EXISTS sublink in the ON clause of an outer join in the parent > query, where the moved qual interacts with the available_rels check. > Agreed and added tests. Thanks! -- Regards, Alena Rybakina Yandex
Re: pull-up subquery if JOIN-ON contains refs to upper-query
I attached the previous version in that letter by mistake, so v10 is actual now with included tests and some more comments about queries in regression test. On 30.09.2026 12:42, Alena Rybakina wrote: > Hi! Thank you for the review! > > On 28.09.2026 18:56, Ilia Evdokimov wrote: >> Hi Alena, >> >> Thanks for v8. The walker is much easier to follow now, and all of >> Peter's points look addressed to me. >> >> I compared the results of random EXISTS/NOT EXISTS queries with and >> without the pull-up (adding OFFSET 0 to the sub-select blocks it). >> The queries had nested inner and outer joins in the sub-select, >> correlated and uncorrelated quals in the ON clauses, and NULLs in the >> data. About 13.5k queries ran, and about 1250 of them go through the >> new code path. I found no wrong results and no assertion failures, so >> the approach looks correct to me. > Thank you for testing! I haven't found any issues either during > Smith's test or in a one-hour SQLancer run. >> >> My main comment is about the regression tests. A few things are >> missing in the regression tests: >> >> 1. anti join cases >> 2. query results not only EXPLAIN output >> 3. An EXISTS sublink in the ON clause of an outer join in the parent >> query, where the moved qual interacts with the available_rels check. >> > Agreed and added tests. Thanks! >
Re: pull-up subquery if JOIN-ON contains refs to upper-query
Hi all, Inspired by the Cloudberry (a Greenplum-based database) bug discussion [0], I added support for pulling up an EXISTS subquery from an outer join’s ON clause when it references both join inputs. This is implemented in the second patch. The implementation shares subquery preparation with the existing semijoin/antijoin conversion. When those transformations are blocked by references to the preserved input, it tries a LEFT JOIN against distinct correlation keys, attached to the nullable input. A CASE expression in the original ON clause checks the match marker and evaluates the remaining correlations. For NOT EXISTS, this fallback is allowed only when all correlation keys are fixed by the nullable input; otherwise, the SubPlan is retained. [0] https://github.com/apache/cloudberry/pull/1933/changes/4e9f8c7db45186b520632803e2eb22a350f5d8b9 I also tested the patches with SQLsmith. The only internal error encountered was the one already reported in [1], which is unrelated to these changes. [1] https://www.postgresql.org/message-id/flat/CACJufxF7iSeRF2%2BbprERSwBe5zShVch1EJK-KcxQCcLT-UHBbg%40mail.gmail.com#bb062383fbe183d923596ede64d1d62f -- Regards, Alena Rybakina Yandex
Re: pull-up subquery if JOIN-ON contains refs to upper-query
Hi Alena,
I reviewed v11-patches.
The 0001-patch LGTM; I have no further comments on it.
For the 0002-patch, I found a performance regression with independent
correlation keys:
```
CREATE TABLE po (x int);
CREATE TABLE pa (x int);
CREATE TABLE pc (x int, y int);
INSERT INTO po VALUES (1);
INSERT INTO pa VALUES (1);
INSERT INTO pc SELECT g, 1 FROM generate_series(1, 100000) g;
CREATE INDEX ON pc (y, x);
ANALYZE po;
ANALYZE pa;
ANALYZE pc;
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF)
SELECT po.x, pa.x
FROM po LEFT JOIN pa
ON EXISTS (
SELECT 1 FROM pc
WHERE pc.y = pa.x AND pc.x = po.x
);
QUERY PLAN
-----------------------------------------------------------------------------
Nested Loop Left Join (actual rows=1.00 loops=1)
Join Filter: CASE WHEN (true) THEN ((pc.x = po.x) IS TRUE) ELSE false END
Rows Removed by Join Filter: 99999
Buffers: shared hit=887 dirtied=1 written=1
-> Seq Scan on po (actual rows=1.00 loops=1)
Buffers: shared hit=1
-> Nested Loop Left Join (actual rows=100000.00 loops=1)
Join Filter: (pc.y = pa.x)
Buffers: shared hit=886 dirtied=1 written=1
-> Seq Scan on pa (actual rows=1.00 loops=1)
Buffers: shared hit=1
-> HashAggregate (actual rows=100000.00 loops=1)
Group Key: pc.y, pc.x
Batches: 1 Memory Usage: 6937kB
Buffers: shared hit=885 dirtied=1 written=1
-> Seq Scan on pc (actual rows=100000.00 loops=1)
Buffers: shared hit=885 dirtied=1 written=1
Planning:
Buffers: shared hit=81 read=9
Planning Time: 1.169 ms
Execution Time: 36.584 ms
(21 rows)
```
Adding OFFSET 0 to the subquery retains the SubPlan:
```
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF)
SELECT po.x, pa.x
FROM po LEFT JOIN pa
ON EXISTS (
SELECT 1 FROM pc
WHERE pc.y = pa.x AND pc.x = po.x
OFFSET 0
);
QUERY PLAN
---------------------------------------------------------------------------
Nested Loop Left Join (actual rows=1.00 loops=1)
Join Filter: EXISTS(SubPlan exists_1)
Buffers: shared hit=5
-> Seq Scan on po (actual rows=1.00 loops=1)
Buffers: shared hit=1
-> Seq Scan on pa (actual rows=1.00 loops=1)
Buffers: shared hit=1
SubPlan exists_1
-> Index Only Scan using pc_y_x_idx on pc (actual rows=1.00 loops=1)
Index Cond: ((y = pa.x) AND (x = po.x))
Heap Fetches: 0
Index Searches: 1
Buffers: shared hit=3
Planning Time: 0.419 ms
Execution Time: 0.209 ms
(15 rows)
```
The fallback groups all 100 000 rows and rejects 99 999 through the
outer case, while SubPlan performs a single index-only search using
boh correlation keys.
How should we choose between these strategies? Currently, the fallback
is selected before path generation, so the original SubPlan is no
longer available for cost comparison.
--
Best regards,
Ilia Evdokimov,
Tantor Labs LLC,
https://tantorlabs.com/