Skip to content

Bug in interpreting correctly parsed SQL with aliases  #4123

@mkmik

Description

@mkmik

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions