@@ -573,17 +573,6 @@ impl TreeNodeRewriter for PullUpCorrelatedExpr {
573573 self . can_pull_up = false ;
574574 return Ok ( Transformed :: new ( plan, false , TreeNodeRecursion :: Stop ) ) ;
575575 }
576- // Only a DISTINCT under EXISTS/IN may skip this check. The pulled
577- // up column becomes an extra group key, which for a DISTINCT only
578- // adds duplicate rows, and EXISTS/IN ignore duplicates. Elsewhere,
579- // e.g. LATERAL, the duplicates reach the result. See #25808.
580- let is_distinct = aggregate. aggr_expr . is_empty ( ) ;
581- let is_exists_or_in =
582- self . exists_sub_query || self . in_predicate_opt . is_some ( ) ;
583- let can_skip_check = is_distinct && is_exists_or_in;
584- if !can_skip_check {
585- self . can_pull_up = self . can_pull_up && self . can_pull_over_aggregation ;
586- }
587576 let mut local_correlated_cols = BTreeSet :: new ( ) ;
588577 collect_local_correlated_cols (
589578 & plan,
@@ -649,6 +638,20 @@ impl TreeNodeRewriter for PullUpCorrelatedExpr {
649638 aggregate. input . schema ( ) ,
650639 ) ?
651640 } ;
641+ // A DISTINCT may skip this check when the pull up adds no group
642+ // key, or under EXISTS/IN. An added key only adds duplicate rows,
643+ // which EXISTS/IN ignore. Elsewhere, e.g. LATERAL, the duplicates
644+ // reach the result. See #25808.
645+ let is_distinct = aggregate. aggr_expr . is_empty ( ) ;
646+ let is_exists_or_in =
647+ self . exists_sub_query || self . in_predicate_opt . is_some ( ) ;
648+ let adds_group_keys = missing_exprs
649+ . iter ( )
650+ . any ( |expr| !aggregate. group_expr . contains ( expr) ) ;
651+ let can_skip_check = is_distinct && ( is_exists_or_in || !adds_group_keys) ;
652+ if !can_skip_check {
653+ self . can_pull_up = self . can_pull_up && self . can_pull_over_aggregation ;
654+ }
652655
653656 // if the original group expressions are empty, need to handle the Count bug
654657 let mut expr_result_map_for_count_bug = HashMap :: new ( ) ;
0 commit comments