jayzhan211 opened a new issue, #27795:
URL: https://github.com/apache/datafusion/issues/27795

   ### Describe the bug
   
   `ORDER BY` on a SELECT alias, by name or by position, silently sorts by a 
different column when two things hold:
   
   - the alias is also the name of an input column that another SELECT item 
reads, and
   - the input columns are unqualified: a derived table or `VALUES` without an 
alias.
   
   Giving the subquery an alias makes the same query return the right order.
   
   ### To Reproduce
   
   Run in `datafusion-cli` built from main (73af333429):
   
   | Query | Actual | Expected |
   |---|---|---|
   | `SELECT price AS old_price, 10 - price AS price FROM (SELECT 1 AS price 
UNION ALL SELECT 5) ORDER BY price;` | `(1, 9), (5, 5)` | `(5, 5), (1, 9)` |
   | Same query with `ORDER BY 2` | `(1, 9), (5, 5)` | `(5, 5), (1, 9)` |
   | Same query with `... SELECT 5) AS s ORDER BY price` | `(5, 5), (1, 9)` | 
`(5, 5), (1, 9)` (correct) |
   | `SELECT column1 AS column2, column2 AS column1 FROM (VALUES (1, 20), (2, 
10)) ORDER BY column1;` | `(1, 20), (2, 10)` | `(2, 10), (1, 20)` |
   
   The logical plan sorts by the other alias:
   
   ```
   Sort: old_price ASC NULLS LAST
     Projection: price AS old_price, Int64(10) - price AS price
   ```
   
   ### Expected behavior
   
   `ORDER BY price` and `ORDER BY 2` sort by the output column `price` (`10 - 
price`). This matches the rule the SQL planner states in `select.rs`: ORDER BY 
prefers columns from the select list.
   
   ### Additional context
   
   **Cause:** the SQL planner resolves the sort key to the output column 
`price` first. `LogicalPlanBuilder::sort` then calls 
`rewrite_in_terms_of_projection` 
(`datafusion/expr/src/expr_rewriter/order_by.rs:75`). That function matches the 
key against the projection's expressions, which are written over the input, and 
it looks inside aliases. So the unqualified input column `price` inside `price 
AS old_price` compares equal to the output column `price`, and the key becomes 
`old_price`. With qualified inputs (`s.price`) the two never compare equal, 
which is why the aliased subquery is correct.
   
   One possible fix, not tried yet: skip the projection match for a sort key 
whose columns already resolve in the projection's output schema.
   
   I found this while reviewing #27773, which avoids the same collision for 
`SELECT DISTINCT` by not rewriting bare columns. Anyone is welcome to pick this 
up; ping me if you'd like pointers.
   


-- 
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]

Reply via email to