@@ -254,12 +254,13 @@ pub(super) fn rewrite_plan_for_sort_on_non_projected_fields(
254254 . map ( |e| map. get ( e) . unwrap_or ( e) . clone ( ) )
255255 . collect :: < Vec < _ > > ( ) ;
256256
257- // Build a reverse map from alias name → underlying expression for
258- // sort columns that are dropped from the outer projection. When
259- // the inner Projection is trimmed to `new_exprs` below, any alias
260- // that only existed in the inner Projection disappears, so ORDER BY
261- // references to it become dangling. We inline the physical
262- // expression instead (e.g. ORDER BY "c" → ORDER BY "Z").
257+ // The inner Projection may define aliases that the Sort references
258+ // but the outer Projection does not include. Since we are about to
259+ // replace the inner Projection's expressions with `new_exprs` (which
260+ // only contains the outer Projection's columns), those alias
261+ // definitions will be lost. To keep the Sort valid, rewrite any
262+ // sort expression that references a dropped alias so that it uses
263+ // the alias's underlying expression instead.
263264 let projected_aliases: HashSet < & str > = new_exprs
264265 . iter ( )
265266 . filter_map ( |e| match e {
@@ -268,7 +269,7 @@ pub(super) fn rewrite_plan_for_sort_on_non_projected_fields(
268269 } )
269270 . collect ( ) ;
270271
271- let alias_to_underlying : HashMap < String , Expr > = inner_p
272+ let dropped_aliases : HashMap < String , Expr > = inner_p
272273 . expr
273274 . iter ( )
274275 . filter_map ( |e| match e {
@@ -279,15 +280,14 @@ pub(super) fn rewrite_plan_for_sort_on_non_projected_fields(
279280 } )
280281 . collect ( ) ;
281282
282- if !alias_to_underlying . is_empty ( ) {
283+ if !dropped_aliases . is_empty ( ) {
283284 for sort_expr in & mut sort. expr {
284285 let mut expr = sort_expr. expr . clone ( ) ;
285286 while let Expr :: Alias ( alias) = expr {
286287 expr = * alias. expr ;
287288 }
288289 if let Expr :: Column ( ref col) = expr {
289- let name = col. name ( ) ;
290- if let Some ( underlying) = alias_to_underlying. get ( name) {
290+ if let Some ( underlying) = dropped_aliases. get ( col. name ( ) ) {
291291 sort_expr. expr = underlying. clone ( ) ;
292292 }
293293 }
0 commit comments