You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@datafusion.apache.org by gi...@apache.org on 2026/10/01 08:45:01 UTC

(datafusion) branch gh-readonly-queue/main/pr-25284-54e32bb7e5c4d9d35d801b4cec5fab8c010a4490 created (now 33e45c7214)

This is an automated email from the ASF dual-hosted git repository.

github-merge-queue[bot] pushed a change to branch gh-readonly-queue/main/pr-25284-54e32bb7e5c4d9d35d801b4cec5fab8c010a4490
in repository https://gitbox.apache.org/repos/asf/datafusion.git


      at 33e45c7214 fix: keep the OFFSET of a correlated EXISTS subquery (#25284)

This branch includes the following new commits:

     new 33e45c7214 fix: keep the OFFSET of a correlated EXISTS subquery (#25284)

The 1 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.



---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@datafusion.apache.org
For additional commands, e-mail: commits-help@datafusion.apache.org


(datafusion) 01/01: fix: keep the OFFSET of a correlated EXISTS subquery (#25284)

Posted by gi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/main/pr-25284-54e32bb7e5c4d9d35d801b4cec5fab8c010a4490
in repository https://gitbox.apache.org/repos/asf/datafusion.git

commit 33e45c721499e0dec0af90caefe3a7dcee4927a0
Author: Fredrik Fornwall <fr...@fornwall.net>
AuthorDate: Thu Oct 1 08:44:36 2026 +0000

    fix: keep the OFFSET of a correlated EXISTS subquery (#25284)
    
    ## Which issue does this PR close?
    
    Closes #25283.
    
    ## Rationale for this change
    
    A correlated `EXISTS` subquery with an `OFFSET` returns wrong results,
    because the `OFFSET` is dropped when the subquery is rewritten into a
    semi join:
    
    ```sql
    CREATE TABLE t1(k INT) AS VALUES (1), (2), (3);
    CREATE TABLE t2(v INT) AS VALUES (1), (1), (3);
    
    SELECT k FROM t1 WHERE EXISTS (SELECT * FROM t2 WHERE t2.v = t1.k OFFSET 1);
    ```
    
    Only `k = 1` has two matching rows, so the expected result is a single
    row with `1` (as SQLite returns). DataFusion returns `1` and `3`. `NOT
    EXISTS` is wrong the same way.
    
    `PullUpCorrelatedExpr` removes the `LIMIT` above the correlated filter
    of an `EXISTS` subquery, since `LIMIT n` with `n > 0` cannot change
    whether any row exists. But the same node carries the `OFFSET`, which
    can turn a non-empty subquery into an empty one.
    
    The decision to remove a `Limit` was also keyed on whether *any*
    correlated predicate had been collected so far, not on whether one sat
    below *this* `Limit`. In a join inside the `EXISTS` the correlated side
    is visited first, so a `LIMIT` on an uncorrelated sibling branch was
    removed too, changing the result:
    
    ```sql
    SELECT t1_id FROM t1 WHERE EXISTS (
      SELECT 1 FROM (SELECT * FROM t2 WHERE t2_id = t1_id) a
      JOIN (SELECT * FROM t3 ORDER BY t3_id LIMIT 1) b ON a.t2_int = b.t3_int)
    ```
    
    With the `subquery.slt` fixtures this returned `11, 22, 44` instead of
    `11, 44`.
    
    ## What changes are included in this PR?
    
    `PullUpCorrelatedExpr` now decides per `Limit`, in `f_down`, whether it
    sits above correlated expressions, using the outer references of its own
    subtree (as it already did for `IN` subqueries), and rewrites the
    `Limit` right there.
    
    For a correlated `EXISTS`, the `Limit` is only removed when it cannot
    change whether the subquery is empty: a zero offset with a literal
    fetch. A zero fetch still becomes an empty relation. Anything else (a
    positive or non-literal offset, or a non-literal fetch) marks the
    subquery as not pull-up-able, so it stays correlated and fails as
    unsupported instead of returning wrong rows.
    
    A `Limit` with no correlated expressions below it is left alone.
    
    ## What is the testing strategy for this PR?
    
    New sqllogictest cases in `subquery.slt`:
    
    - `LIMIT 1 OFFSET 0` is still decorrelated.
    - `OFFSET 1` keeps the subquery correlated, and running the query fails
    with a not-implemented error. The explain case fails without the fix.
    The same for `NOT EXISTS`, and for `EXISTS` in a disjunction.
    - `LIMIT 0 OFFSET 1` still becomes an empty relation.
    - A non-literal `LIMIT` keeps the subquery correlated.
    - A `LIMIT` or `OFFSET` on an uncorrelated branch of a join inside the
    `EXISTS` is kept and the query returns the correct rows. Both fail
    without the per-`Limit` decision.
    
    ## Are there any user-facing changes?
    
    - A correlated `EXISTS` / `NOT EXISTS` subquery with a positive
    `OFFSET`, or with a non-literal `LIMIT`, now fails with a
    not-implemented error instead of returning wrong results (previously the
    `LIMIT` / `OFFSET` was silently dropped). I can file an issue and take a
    stab at supporting these in a follow-up once this is merged.
    - A `LIMIT` or `OFFSET` on an uncorrelated branch inside a correlated
    `EXISTS` subquery is no longer dropped, so such queries now return
    correct results.
    
    Disclaimer: Created with fable 5.1 in claude code. I have reviewed the
    code.
    
    ---------
    
    Signed-off-by: Fredrik Fornwall <fr...@fornwall.net>
    Co-authored-by: kosiew <ko...@gmail.com>
---
 datafusion/optimizer/src/decorrelate.rs         |  74 ++++++-----
 datafusion/sqllogictest/test_files/subquery.slt | 156 ++++++++++++++++++++++++
 2 files changed, 197 insertions(+), 33 deletions(-)

diff --git a/datafusion/optimizer/src/decorrelate.rs b/datafusion/optimizer/src/decorrelate.rs
index 50c34d439f..186d7a9bbe 100644
--- a/datafusion/optimizer/src/decorrelate.rs
+++ b/datafusion/optimizer/src/decorrelate.rs
@@ -37,7 +37,7 @@ use datafusion_expr::utils::{
 };
 use datafusion_expr::{
     BinaryExpr, Cast, EmptyRelation, Expr, ExprSchemable, FetchType, LogicalPlan,
-    LogicalPlanBuilder, Operator, expr, lit,
+    LogicalPlanBuilder, Operator, SkipType, expr, lit,
 };
 
 /// This struct rewrite the sub query plan by pull up the correlated
@@ -135,6 +135,13 @@ impl PullUpCorrelatedExpr {
         self.exists_sub_query = exists_sub_query;
         self
     }
+
+    /// Mark the plan as one whose correlated expressions cannot be pulled up
+    /// and stop descending into it
+    fn unsupported(&mut self, plan: LogicalPlan) -> Result<Transformed<LogicalPlan>> {
+        self.can_pull_up = false;
+        Ok(Transformed::new(plan, false, TreeNodeRecursion::Jump))
+    }
 }
 
 /// Used to indicate the unmatched rows from the inner(subquery) table after the left out Join
@@ -174,28 +181,44 @@ impl TreeNodeRewriter for PullUpCorrelatedExpr {
             LogicalPlan::Union(_) | LogicalPlan::Sort(_) | LogicalPlan::Extension(_) => {
                 let plan_hold_outer = !plan.all_out_ref_exprs().is_empty();
                 if plan_hold_outer {
-                    // the unsupported case
-                    self.can_pull_up = false;
-                    Ok(Transformed::new(plan, false, TreeNodeRecursion::Jump))
+                    self.unsupported(plan)
                 } else {
                     Ok(Transformed::no(plan))
                 }
             }
-            LogicalPlan::Limit(_) => {
-                let plan_hold_outer = !plan.all_out_ref_exprs().is_empty();
-                match (self.exists_sub_query, plan_hold_outer) {
-                    (false, true) => {
-                        // the unsupported case
-                        self.can_pull_up = false;
-                        Ok(Transformed::new(plan, false, TreeNodeRecursion::Jump))
+            LogicalPlan::Limit(ref limit) => {
+                if plan.all_out_ref_exprs().is_empty() {
+                    return Ok(Transformed::no(plan));
+                }
+                if !self.exists_sub_query {
+                    return self.unsupported(plan);
+                }
+                // Only emptiness matters for EXISTS, so remove a limit that
+                // cannot make its input empty and replace one that always does
+                // with an empty relation.
+                let fetch = limit.get_fetch_type()?;
+                if matches!(fetch, FetchType::Literal(Some(0))) {
+                    return Ok(Transformed::yes(LogicalPlan::EmptyRelation(
+                        EmptyRelation {
+                            produce_one_row: false,
+                            schema: Arc::clone(limit.input.schema()),
+                        },
+                    )));
+                }
+                match (limit.get_skip_type()?, fetch) {
+                    (SkipType::Literal(0), FetchType::Literal(_)) => {
+                        // The rewriter does not call `f_down` on the returned
+                        // node, so do it here
+                        let mut t = self.f_down((*limit.input).clone())?;
+                        t.transformed = true;
+                        Ok(t)
                     }
-                    _ => Ok(Transformed::no(plan)),
+                    _ => self.unsupported(plan),
                 }
             }
             _ if plan.contains_outer_reference() => {
                 // the unsupported cases, the plan expressions contain out reference columns(like window expressions)
-                self.can_pull_up = false;
-                Ok(Transformed::new(plan, false, TreeNodeRecursion::Jump))
+                self.unsupported(plan)
             }
             _ => Ok(Transformed::no(plan)),
         }
@@ -455,28 +478,13 @@ impl TreeNodeRewriter for PullUpCorrelatedExpr {
                 }
             }
             LogicalPlan::Limit(limit) => {
-                let input_expr_map =
-                    self.collected_count_expr_map.get(&*limit.input).cloned();
-                // handling the limit clause in the subquery
-                let new_plan = match (self.exists_sub_query, self.join_filters.is_empty())
+                if let Some(input_map) =
+                    self.collected_count_expr_map.get(&*limit.input).cloned()
                 {
-                    // Correlated exist subquery, remove the limit(so that correlated expressions can pull up)
-                    (true, false) => Transformed::yes(match limit.get_fetch_type()? {
-                        FetchType::Literal(Some(0)) => {
-                            LogicalPlan::EmptyRelation(EmptyRelation {
-                                produce_one_row: false,
-                                schema: Arc::clone(limit.input.schema()),
-                            })
-                        }
-                        _ => LogicalPlanBuilder::from((*limit.input).clone()).build()?,
-                    }),
-                    _ => Transformed::no(plan),
-                };
-                if let Some(input_map) = input_expr_map {
                     self.collected_count_expr_map
-                        .insert(new_plan.data.clone(), input_map);
+                        .insert(plan.clone(), input_map);
                 }
-                Ok(new_plan)
+                Ok(Transformed::no(plan))
             }
             _ => Ok(Transformed::no(plan)),
         }
diff --git a/datafusion/sqllogictest/test_files/subquery.slt b/datafusion/sqllogictest/test_files/subquery.slt
index 7c5c0b76bc..8ab3d518fa 100644
--- a/datafusion/sqllogictest/test_files/subquery.slt
+++ b/datafusion/sqllogictest/test_files/subquery.slt
@@ -656,6 +656,142 @@ SELECT t1_id, t1_name FROM t1 WHERE NOT EXISTS (SELECT * FROM t2 WHERE t2_id = t
 33 c
 44 d
 
+#exists_subquery_with_offset0
+#de-correlated, limit is removed
+query TT
+explain SELECT t1_id, t1_name FROM t1 WHERE EXISTS (SELECT * FROM t2 WHERE t2_id = t1_id limit 1 offset 0)
+----
+logical_plan
+01)LeftSemi Join: t1.t1_id = __correlated_sq_1.t2_id
+02)--TableScan: t1 projection=[t1_id, t1_name]
+03)--SubqueryAlias: __correlated_sq_1
+04)----TableScan: t2 projection=[t2_id]
+
+query IT rowsort
+SELECT t1_id, t1_name FROM t1 WHERE EXISTS (SELECT * FROM t2 WHERE t2_id = t1_id limit 1 offset 0)
+----
+11 a
+22 b
+44 d
+
+#exists_subquery_with_offset
+#not de-correlated, the offset could make the subquery empty
+query TT
+explain SELECT t1_id, t1_name FROM t1 WHERE EXISTS (SELECT * FROM t2 WHERE t2_id = t1_id offset 1)
+----
+logical_plan
+01)Filter: EXISTS (<subquery>)
+02)--Subquery:
+03)----Limit: skip=1, fetch=None
+04)------Projection: t2.t2_id, t2.t2_name, t2.t2_int
+05)--------Filter: t2.t2_id = outer_ref(t1.t1_id)
+06)----------TableScan: t2
+07)--TableScan: t1 projection=[t1_id, t1_name]
+
+# errors rather than returning wrong rows
+query error Physical plan does not support logical expression Exists
+SELECT t1_id, t1_name FROM t1 WHERE EXISTS (SELECT * FROM t2 WHERE t2_id = t1_id offset 1)
+
+#not_exists_subquery_with_offset
+#not de-correlated, the offset could make the subquery empty
+query TT
+explain SELECT t1_id, t1_name FROM t1 WHERE NOT EXISTS (SELECT * FROM t2 WHERE t2_id = t1_id offset 1)
+----
+logical_plan
+01)Filter: NOT EXISTS (<subquery>)
+02)--Subquery:
+03)----Limit: skip=1, fetch=None
+04)------Projection: t2.t2_id, t2.t2_name, t2.t2_int
+05)--------Filter: t2.t2_id = outer_ref(t1.t1_id)
+06)----------TableScan: t2
+07)--TableScan: t1 projection=[t1_id, t1_name]
+
+# errors rather than returning wrong rows
+query error Physical plan does not support logical expression Exists
+SELECT t1_id, t1_name FROM t1 WHERE NOT EXISTS (SELECT * FROM t2 WHERE t2_id = t1_id offset 1)
+
+#exists_subquery_with_offset_in_disjunction
+#not de-correlated, errors rather than returning wrong rows
+query error Physical plan does not support logical expression Exists
+SELECT t1_id, t1_name FROM t1 WHERE t1_id > 40 OR EXISTS (SELECT * FROM t2 WHERE t2_id = t1_id offset 1)
+
+#exists_subquery_with_limit0_and_offset
+#de-correlated, limit 0 is empty whatever the offset
+query TT
+explain SELECT t1_id, t1_name FROM t1 WHERE EXISTS (SELECT * FROM t2 WHERE t2_id = t1_id limit 0 offset 1)
+----
+logical_plan EmptyRelation: rows=0
+
+query IT rowsort
+SELECT t1_id, t1_name FROM t1 WHERE EXISTS (SELECT * FROM t2 WHERE t2_id = t1_id limit 0 offset 1)
+----
+
+#exists_subquery_with_non_literal_limit
+#not de-correlated, the fetch could evaluate to 0 and make the subquery empty
+query TT
+explain SELECT t1_id, t1_name FROM t1 WHERE EXISTS (SELECT * FROM t2 WHERE t2_id = t1_id limit (SELECT count(*) FROM t2))
+----
+logical_plan
+01)Filter: EXISTS (<subquery>)
+02)--Subquery:
+03)----Limit: skip=0, fetch=(<subquery>)
+04)------Subquery:
+05)--------Projection: count(Int64(1)) AS count(*)
+06)----------Aggregate: groupBy=[[]], aggr=[[count(Int64(1))]]
+07)------------TableScan: t2
+08)------Projection: t2.t2_id, t2.t2_name, t2.t2_int
+09)--------Filter: t2.t2_id = outer_ref(t1.t1_id)
+10)----------TableScan: t2
+11)--TableScan: t1 projection=[t1_id, t1_name]
+
+#exists_subquery_with_non_literal_offset
+#not de-correlated, the offset could be positive and make the subquery empty
+query TT
+explain SELECT t1_id, t1_name FROM t1 WHERE EXISTS (SELECT * FROM t2 WHERE t2_id = t1_id offset (SELECT 1))
+----
+logical_plan
+01)Filter: EXISTS (<subquery>)
+02)--Subquery:
+03)----Limit: skip=(<subquery>), fetch=None
+04)------Subquery:
+05)--------Projection: Int64(1)
+06)----------EmptyRelation: rows=1
+07)------Projection: t2.t2_id, t2.t2_name, t2.t2_int
+08)--------Filter: t2.t2_id = outer_ref(t1.t1_id)
+09)----------TableScan: t2
+10)--TableScan: t1 projection=[t1_id, t1_name]
+
+#exists_subquery_with_limit_on_uncorrelated_branch
+#de-correlated, the limit is on an uncorrelated branch so it stays
+query TT
+explain SELECT t1_id FROM t1 WHERE EXISTS (SELECT 1 FROM (SELECT * FROM t2 WHERE t2_id = t1_id) a JOIN (SELECT * FROM t3 ORDER BY t3_id LIMIT 1) b ON a.t2_int = b.t3_int)
+----
+logical_plan
+01)LeftSemi Join: t1.t1_id = __correlated_sq_1.t2_id
+02)--TableScan: t1 projection=[t1_id]
+03)--SubqueryAlias: __correlated_sq_1
+04)----Projection: a.t2_id
+05)------LeftSemi Join: a.t2_int = b.t3_int
+06)--------SubqueryAlias: a
+07)----------TableScan: t2 projection=[t2_id, t2_int]
+08)--------SubqueryAlias: b
+09)----------Projection: t3.t3_int
+10)------------Sort: t3.t3_id ASC NULLS LAST, fetch=1
+11)--------------TableScan: t3 projection=[t3_id, t3_int]
+
+query I rowsort
+SELECT t1_id FROM t1 WHERE EXISTS (SELECT 1 FROM (SELECT * FROM t2 WHERE t2_id = t1_id) a JOIN (SELECT * FROM t3 ORDER BY t3_id LIMIT 1) b ON a.t2_int = b.t3_int)
+----
+11
+44
+
+#exists_subquery_with_offset_on_uncorrelated_branch
+#de-correlated, the offset is on an uncorrelated branch so it stays
+query I rowsort
+SELECT t1_id FROM t1 WHERE EXISTS (SELECT 1 FROM (SELECT * FROM t2 WHERE t2_id = t1_id) a JOIN (SELECT * FROM t3 ORDER BY t3_id LIMIT 1 OFFSET 1) b ON a.t2_int = b.t3_int)
+----
+22
+
 #in_correlated_subquery_with_limit
 #not de-correlated
 query TT
@@ -717,6 +853,26 @@ logical_plan
 09)----------TableScan: t2
 10)--TableScan: t1 projection=[t1_id, t1_name]
 
+#exists_subquery_with_limit_over_union
+#not de-correlated, the union below the removed limit still holds outer references
+query TT
+explain SELECT t1_id, t1_name FROM t1 WHERE EXISTS (SELECT * FROM t2 WHERE t2_id = t1_id UNION ALL SELECT * FROM t2 WHERE upper(t2_name) = upper(t1.t1_name) LIMIT 1)
+----
+logical_plan
+01)Filter: EXISTS (<subquery>)
+02)--Subquery:
+03)----Limit: skip=0, fetch=1
+04)------Union
+05)--------Projection: t2.t2_id, t2.t2_name, t2.t2_int
+06)----------Limit: skip=0, fetch=1
+07)------------Filter: t2.t2_id = outer_ref(t1.t1_id)
+08)--------------TableScan: t2
+09)--------Projection: t2.t2_id, t2.t2_name, t2.t2_int
+10)----------Limit: skip=0, fetch=1
+11)------------Filter: upper(t2.t2_name) = upper(outer_ref(t1.t1_name))
+12)--------------TableScan: t2
+13)--TableScan: t1 projection=[t1_id, t1_name]
+
 #simple_uncorrelated_scalar_subquery
 query TT
 explain select (select count(*) from t1) as b


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@datafusion.apache.org
For additional commands, e-mail: commits-help@datafusion.apache.org