diff --git a/datafusion/sql/src/select.rs b/datafusion/sql/src/select.rs index 7862715e5f1d3..f47720d4674ac 100644 --- a/datafusion/sql/src/select.rs +++ b/datafusion/sql/src/select.rs @@ -88,8 +88,11 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> { // having and group by clause may reference aliases defined in select projection let projected_plan = self.project(base_plan.clone(), select_exprs.clone())?; - let mut combined_schema = (**projected_plan.schema()).clone(); - combined_schema.merge(base_plan.schema()); + // Place the fields of the base plan at the front so that when there are references + // with the same name, the fields of the base plan will be searched first. + // See https://github.com/apache/arrow-datafusion/issues/9162 + let mut combined_schema = base_plan.schema().as_ref().clone(); + combined_schema.merge(projected_plan.schema()); // this alias map is resolved and looked up in both having exprs and group by exprs let alias_map = extract_aliases(&select_exprs); diff --git a/datafusion/sqllogictest/test_files/aggregate.slt b/datafusion/sqllogictest/test_files/aggregate.slt index 136fb39c673ec..f50134e63509d 100644 --- a/datafusion/sqllogictest/test_files/aggregate.slt +++ b/datafusion/sqllogictest/test_files/aggregate.slt @@ -3179,3 +3179,23 @@ NULL statement ok DROP TABLE t; + +# Test for the case when the column name is ambiguous +statement ok +CREATE TABLE t(a BIGINT) AS VALUES(1), (2), (3); + +# The column name referenced by GROUP-BY is ambiguous, prefer the column in base plan +query I +SELECT 0 as "t.a" FROM t GROUP BY t.a; +---- +0 +0 +0 + +# The column name referenced by HAVING is ambiguous, prefer the column in the base plan +query I +SELECT 0 AS "t.a" FROM t HAVING MAX(t.a) = 0; +---- + +statement ok +DROP TABLE t; \ No newline at end of file