diff --git a/src/query/sql/src/planner/optimizer/rule/rewrite/rule_push_down_filter_union.rs b/src/query/sql/src/planner/optimizer/rule/rewrite/rule_push_down_filter_union.rs index 96cd7d560002..eff9e73861a1 100644 --- a/src/query/sql/src/planner/optimizer/rule/rewrite/rule_push_down_filter_union.rs +++ b/src/query/sql/src/planner/optimizer/rule/rewrite/rule_push_down_filter_union.rs @@ -72,6 +72,11 @@ impl Rule for RulePushDownFilterUnion { let filter: Filter = s_expr.plan().clone().try_into()?; let union_s_expr = s_expr.child(0)?; let union: UnionAll = union_s_expr.plan().clone().try_into()?; + if !union.cte_scan_names.is_empty() { + // If the union has cte scan names, it's not allowed to push down filter. + state.add_result(s_expr.clone()); + return Ok(()); + } // Create a filter which matches union's right child. let index_pairs: HashMap = union diff --git a/tests/sqllogictests/suites/query/cte/r_cte_union_all.test b/tests/sqllogictests/suites/query/cte/r_cte_union_all.test index 18020f8c3da5..2541cdc442a9 100644 --- a/tests/sqllogictests/suites/query/cte/r_cte_union_all.test +++ b/tests/sqllogictests/suites/query/cte/r_cte_union_all.test @@ -76,3 +76,43 @@ SELECT * FROM t; 7 8 9 + +# bug: https://github.com/databendlabs/databend/issues/17027 +statement ok +CREATE or replace TABLE parent_child +( + parent VARCHAR(30), + child VARCHAR(30) +); + +statement ok +INSERT INTO parent_child +VALUES ('Org','Org'),('Org','Global'),('Global','North'), +('Global','South'),('Global','East'),('Global','West'), +('Global','Org detail'),('North','North East'),('North','North West'); + +query I +WITH RECURSIVE tree_values + (parent, child) +AS ( + SELECT parent, child + FROM parent_child + WHERE parent = child + UNION ALL + SELECT c.parent, c.child + FROM parent_child c + INNER JOIN tree_values p + ON p.child = c.parent + WHERE c.parent != c.child +) +select parent, child from tree_values +where parent = 'Global'; +---- +Global East +Global North +Global Org detail +Global South +Global West + +statement ok +drop table parent_child;