@@ -832,6 +832,16 @@ impl OptimizerRule for PushDownFilter {
832832 insert_below ( LogicalPlan :: Distinct ( distinct) , new_filter)
833833 }
834834 LogicalPlan :: Sort ( sort) => {
835+ // If the sort has a fetch (limit), pushing a filter below
836+ // it would change semantics: the limit should apply before
837+ // the filter, not after.
838+ if sort. fetch . is_some ( ) {
839+ let plan = LogicalPlan :: Filter ( Filter :: try_new (
840+ filter. predicate ,
841+ Arc :: new ( LogicalPlan :: Sort ( sort) ) ,
842+ ) ?) ;
843+ return Ok ( Transformed :: no ( plan) ) ;
844+ }
835845 let new_filter =
836846 Filter :: try_new ( filter. predicate , Arc :: clone ( & sort. input ) )
837847 . map ( LogicalPlan :: Filter ) ?;
@@ -4315,4 +4325,40 @@ mod tests {
43154325 "
43164326 )
43174327 }
4328+
4329+ #[ test]
4330+ fn filter_push_down_through_sort_without_fetch ( ) -> Result < ( ) > {
4331+ let table_scan = test_table_scan ( ) ?;
4332+ let plan = LogicalPlanBuilder :: from ( table_scan)
4333+ . sort ( vec ! [ col( "a" ) . sort( true , true ) ] ) ?
4334+ . filter ( col ( "a" ) . gt ( lit ( 10i64 ) ) ) ?
4335+ . build ( ) ?;
4336+ // Filter should be pushed below the sort
4337+ assert_optimized_plan_equal ! (
4338+ plan,
4339+ @r"
4340+ Sort: test.a ASC NULLS FIRST
4341+ TableScan: test, full_filters=[test.a > Int64(10)]
4342+ "
4343+ )
4344+ }
4345+
4346+ #[ test]
4347+ fn filter_not_pushed_down_through_sort_with_fetch ( ) -> Result < ( ) > {
4348+ let table_scan = test_table_scan ( ) ?;
4349+ let plan = LogicalPlanBuilder :: from ( table_scan)
4350+ . sort_with_limit ( vec ! [ col( "a" ) . sort( true , true ) ] , Some ( 5 ) ) ?
4351+ . filter ( col ( "a" ) . gt ( lit ( 10i64 ) ) ) ?
4352+ . build ( ) ?;
4353+ // Filter must NOT be pushed below the sort when it has a fetch (limit),
4354+ // because the limit should apply before the filter.
4355+ assert_optimized_plan_equal ! (
4356+ plan,
4357+ @r"
4358+ Filter: test.a > Int64(10)
4359+ Sort: test.a ASC NULLS FIRST, fetch=5
4360+ TableScan: test
4361+ "
4362+ )
4363+ }
43184364}
0 commit comments