Skip to content

fix(sql): SELECT DISTINCT with ORDER BY on a projected expression - #27773

Open
TinyMurky wants to merge 3 commits into
apache:mainfrom
TinyMurky:fix/27705-distinct-order-by-expression
Open

TinyMurky wants to merge 3 commits into
apache:mainfrom
TinyMurky:fix/27705-distinct-order-by-expression

Conversation

@TinyMurky

Copy link
Copy Markdown
Contributor

Which issue does this PR close?

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.

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.

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.

@github-actions github-actions Bot added sql SQL Planner sqllogictest SQL Logic Tests (.slt) labels Nov 26, 2026
@TinyMurky

TinyMurky commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor Author

Hi @jayzhan211!

Could you review this PR when/if you have a chance?

Thank you!!!

@jayzhan211 jayzhan211 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@TinyMurky thanks! One small ask inline: a test for the Expr::Column skip, which keeps swapped alias names correct.

Comment thread datafusion/sql/src/select.rs Outdated
Comment on lines +576 to +578
if matches!(sort.expr, Expr::Column(_)) {
continue;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@TinyMurky thanks for the fix! This Expr::Column skip is what keeps a bare output name from matching an input column with the same name, but no test fails if it's removed. Without it, SELECT DISTINCT column1 AS column2, column2 AS column1 FROM (VALUES (1, 20), (2, 10)) ORDER BY column1 returns (1, 20), (2, 10) instead of (2, 10), (1, 20). Could you add a comment saying why, and this case to order.slt?

Suggested change
if matches!(sort.expr, Expr::Column(_)) {
continue;
}
// A bare column may name an output column whose name an input
// column in another expression shares, e.g. ORDER BY column1 in
// SELECT DISTINCT column1 AS column2, column2 AS column1.
if matches!(sort.expr, Expr::Column(_)) {
continue;
}
# ORDER BY column1 names the output column1 (input column2), not the input
# column1 that the first SELECT expression reads
query II
SELECT DISTINCT column1 AS column2, column2 AS column1
FROM (VALUES (1, 20), (2, 10))
ORDER BY column1;
----
2 10
1 20

@TinyMurky TinyMurky Nov 29, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hello !@jayzhan211

I had added the test and the comment in the new commit!

@jayzhan211 jayzhan211 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@TinyMurky thanks for the update! One more case inline: a computed sort key can still hit the same name collision, so the result depends on whether the subquery has an alias.

Comment on lines +575 to +581
for sort in &mut order_by_rex {
// A bare column may name an output column whose name an input
// column in another expression shares, e.g. ORDER BY column1 in
// SELECT DISTINCT column1 AS column2, column2 AS column1.
if matches!(sort.expr, Expr::Column(_)) {
continue;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@TinyMurky thanks for adding the test! One more case: a computed key can still hit the same name collision, and then the result depends on whether the subquery has an alias. SELECT DISTINCT price AS old_price, 10 - price AS price FROM (SELECT 1 AS price UNION ALL SELECT 5) ORDER BY 10 - price returns (5, 5), (1, 9). With AS s after the subquery it returns (1, 9), (5, 5). Main returns (1, 9), (5, 5) for both.

price in the key resolves to the output price, but it compares equal to the unqualified input price inside 10 - price AS price. Skipping any key that reads a renamed output fixes this, and it also covers the bare-column case, so the Expr::Column check can go:

Suggested change
for sort in &mut order_by_rex {
// A bare column may name an output column whose name an input
// column in another expression shares, e.g. ORDER BY column1 in
// SELECT DISTINCT column1 AS column2, column2 AS column1.
if matches!(sort.expr, Expr::Column(_)) {
continue;
}
// ORDER BY names resolve to SELECT outputs first, but
// projection.expr reads input columns. With an unqualified input
// (VALUES or a subquery without an alias), the output column1 of
// column2 AS column1 equals the input column1, so a key that
// reads a renamed output is not matched.
let renamed_outputs: Vec<Column> = projection
.expr
.iter()
.zip(projection.schema.columns())
.filter(|(expr, output)| {
!matches!(expr, Expr::Column(input) if input == output)
})
.map(|(_, output)| output)
.collect();
for sort in &mut order_by_rex {
if sort
.expr
.column_refs()
.iter()
.any(|col| renamed_outputs.contains(col))
{
continue;
}
Tests for order.slt, after the swapped-alias test (the first two pin the alias case; the third separates this rule from "skip any key that reads an output column")
# price in ORDER BY names the output price, with or without the subquery alias
query II
SELECT DISTINCT price AS old_price, 10 - price AS price
FROM (SELECT 1 AS price UNION ALL SELECT 5)
ORDER BY 10 - price;
----
1 9
5 5

query II
SELECT DISTINCT price AS old_price, 10 - price AS price
FROM (SELECT 1 AS price UNION ALL SELECT 5) AS s
ORDER BY 10 - price;
----
1 9
5 5

# a key that reads a selected column and an unselected one still matches a + b
query II
SELECT DISTINCT a, a + b AS v
FROM (VALUES (2, 1), (1, 5), (2, 1)) AS input(a, b)
ORDER BY a + b;
----
2 3
1 6

With this change, the full sqllogictest suite, cargo test -p datafusion-sql and clippy pass locally.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jayzhan211 I have changed the codes and added the tests
Could you review the changesif you have a chance?

@TinyMurky
TinyMurky force-pushed the fix/27705-distinct-order-by-expression branch from 189f7c0 to 392300b Compare December 6, 2026 20:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

sql SQL Planner sqllogictest SQL Logic Tests (.slt)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

SELECT DISTINCT fails when ORDER BY repeats a projected arithmetic expression

2 participants