-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Description
Describe the bug
Some statements that involve subqueries with an alias, are not evaluated correctly when the subquery contains both group by and order by.
To Reproduce
With datafusion-cli:
❯ select a from (select a from (select 1 as a) as foo group by 1 order by a) as c;
SchemaError(FieldNotFound { field: Column { relation: Some("foo"), name: "a" }, valid_fields: Some([Column { relation: Some("c"), name: "a" }]) })Expected behavior
❯ select a from (select a from (select 1 as a) as foo group by 1 order by a) as c;
+---+
| a |
+---+
| 1 |
+---+
1 row in set. Query took 0.005 seconds.(it works on postgres and sqlite)
Additional context
Same happens if there is an actual table called foo:
❯ create table foo as select 1 as a;
0 rows in set. Query took 0.032 seconds.
❯ select a from (select a from foo group by 1 order by a) as c;
SchemaError(FieldNotFound { field: Column { relation: Some("foo"), name: "a" }, valid_fields: Some([Column { relation: Some("c"), name: "a" }]) })Interestingly if I remove as c in the outer expression it works:
❯ select a from (select a from (select 1 as a) as foo group by 1 order by a);
+---+
| a |
+---+
| 1 |
+---+
1 row in set. Query took 0.005 seconds.It's also interesting that using positional column references in the order by works:
❯ select a from (select a from (select 1 as a) as foo group by 1 order by 1) as c;
+---+
| a |
+---+
| 1 |
+---+
1 row in set. Query took 0.005 seconds.Furthermore, the bug reproduces only if group by a and order by a are both present:
❯ select a from (select a from (select 1 as a) as foo group by a) as c;
+---+
| a |
+---+
| 1 |
+---+
1 row in set. Query took 0.005 seconds.
❯ select a from (select a from (select 1 as a) as foo order by a) as c;
+---+
| a |
+---+
| 1 |
+---+
1 row in set. Query took 0.004 seconds.It appears that the alias applied to a subquery somehow affects the field references inside the subquery. For example this this should return an error because c is not defined inside the select a from foo group by 1 order by c.a query:
❯ select a from (select a from foo group by 1 order by c.a) as c;
+---+
| a |
+---+
| 1 |
+---+
1 row in set. Query took 0.024 seconds.