TinyMurky opened a new pull request, #27773: URL: https://github.com/apache/datafusion/pull/27773
## Which issue does this PR close? - Closes #27705. ## Rationale for this change DataFusion can reject a valid `SELECT DISTINCT` query when `ORDER BY` repeats an expression from the SELECT list. This happens with or without an alias. ```sql CREATE TABLE t AS SELECT * FROM (VALUES (2), (1), (2)) AS input(a); SELECT DISTINCT a + 1 FROM t ORDER BY a + 1; SELECT DISTINCT a + 1 AS v FROM t ORDER BY a + 1; ``` Both queries should return `2` and `3` in that order. Before the fix, both fail with an error saying that `t.a` must appear in the SELECT list. This example selects two columns and sorts by both expressions. ```sql CREATE TABLE t2 AS SELECT * FROM (VALUES (2, 1), (1, 1), (1, 3), (2, 2), (1, 3)) AS input(a, b); SELECT DISTINCT a + 1 AS v, b * 2 AS w FROM t2 ORDER BY a + 1, b * 2 DESC; ``` The result is `(2, 6)`, `(2, 2)`, `(3, 4)`, and `(3, 2)`. It sorts by `v` in ascending order and by `w` in descending order within each `v`. ## What changes are included in this PR? The planner now matches computed `ORDER BY` expressions to expressions in the SELECT list, ignoring aliases during the comparison. It sorts by the matching output column. For example, the second query above sorts by `v`. ## What is the testing strategy for this PR? Added cases to `datafusion/sqllogictest/test_files/order.slt` for expressions with and without aliases, descending order with `NULLS LAST`, and multiple sort keys. A query that sorts by an unselected expression, `a + 2`, still returns a planning error. ## Are there any user-facing changes? The queries above now return the expected rows. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
