diff --git a/datafusion/sql/src/unparser/plan.rs b/datafusion/sql/src/unparser/plan.rs index c4fcbb2d6458..d150f0e532c6 100644 --- a/datafusion/sql/src/unparser/plan.rs +++ b/datafusion/sql/src/unparser/plan.rs @@ -357,6 +357,12 @@ impl Unparser<'_> { return self.derive(plan, relation); } if let Some(query_ref) = query { + if let Some(fetch) = sort.fetch { + query_ref.limit(Some(ast::Expr::Value(ast::Value::Number( + fetch.to_string(), + false, + )))); + } query_ref.order_by(self.sorts_to_sql(sort.expr.clone())?); } else { return internal_err!( diff --git a/datafusion/sql/tests/cases/plan_to_sql.rs b/datafusion/sql/tests/cases/plan_to_sql.rs index 903d4e28520b..aff9f99c8cd3 100644 --- a/datafusion/sql/tests/cases/plan_to_sql.rs +++ b/datafusion/sql/tests/cases/plan_to_sql.rs @@ -841,6 +841,26 @@ fn test_table_scan_pushdown() -> Result<()> { Ok(()) } +#[test] +fn test_sort_with_push_down_fetch() -> Result<()> { + let schema = Schema::new(vec![ + Field::new("id", DataType::Utf8, false), + Field::new("age", DataType::Utf8, false), + ]); + + let plan = table_scan(Some("t1"), &schema, None)? + .project(vec![col("id"), col("age")])? + .sort_with_limit(vec![col("age").sort(true, true)], Some(10))? + .build()?; + + let sql = plan_to_sql(&plan)?; + assert_eq!( + format!("{}", sql), + "SELECT t1.id, t1.age FROM t1 ORDER BY t1.age ASC NULLS FIRST LIMIT 10" + ); + Ok(()) +} + #[test] fn test_interval_lhs_eq() { sql_round_trip(