Skip to content

Apache DataFusion SQL Query Engine

fix: disallow specify both order_by and within_group (#16606)

haiywu1c0dcad2d8e0
diff --git a/datafusion/sql/src/expr/function.rs b/datafusion/sql/src/expr/function.rs
index 8a4bbb683b..6b23bd5c2c 100644
--- a/datafusion/sql/src/expr/function.rs
+++ b/datafusion/sql/src/expr/function.rs
@@ -227,6 +227,10 @@ impl<S: ContextProvider> SqlToRel<'_, S> {
OVER is for window functions, whereas WITHIN GROUP is for ordered set aggregate functions");
}
+ if !order_by.is_empty() && !within_group.is_empty() {
+ return plan_err!("ORDER BY and WITHIN GROUP clauses cannot be used together in the same aggregate function. ");
+ }
+
// If function is a window function (it has an OVER clause),
// it shouldn't have ordering requirement as function argument
// required ordering should be defined in OVER clause.
diff --git a/datafusion/sqllogictest/test_files/aggregate.slt b/datafusion/sqllogictest/test_files/aggregate.slt
index 53562d019c..5d6ef1e785 100644
--- a/datafusion/sqllogictest/test_files/aggregate.slt
+++ b/datafusion/sqllogictest/test_files/aggregate.slt
@@ -7053,3 +7053,6 @@ FROM (VALUES ('a'), ('d'), ('c'), ('a')) t(a_varchar);
----
[a, c, d]
+query error Error during planning: ORDER BY and WITHIN GROUP clauses cannot be used together in the same aggregate function.
+SELECT array_agg(a_varchar order by a_varchar) WITHIN GROUP (ORDER BY a_varchar)
+FROM (VALUES ('a'), ('d'), ('c'), ('a')) t(a_varchar);