Skip to content

SELECT DISTINCT with Delimited Alias in ORDER BY Errors (Case Sensitivity) #26755

@jimsimon-wk

Description

@jimsimon-wk

A query using SELECT DISTINCT fails when attempting to order by a column alias that is a delimited identifier (e.g., "x"), even though the unquoted ORDER BY expression (X) should resolve to it via case-insensitive matching.

This specific issue—the failure to resolve the case-insensitive ORDER BY expression to the alias in a DISTINCT context—was previously addressed and fixed in PR #4233.

I suspect this to be a side effect of the modifications to Identifier#getCanonicalValue introduced by PR #6550, which appears to have broken the case-insensitive matching for delimited aliases in the ORDER BY clause.

The following minimal, reproducible example demonstrates the failure:

SELECT DISTINCT a as "x" FROM (VALUES 2, 1, 2) t(a) ORDER BY X

Expected Behavior
The query should execute resolving the identifier in the ORDER BY scope to reference the alias in the SELECT, regardless of case.

Actual Behavior

line 1:1: For SELECT DISTINCT, ORDER BY expressions must appear in select list

Here's patch for a reproducing test

diff --git a/core/trino-main/src/test/java/io/trino/sql/query/TestDistinctWithOrderBy.java b/core/trino-main/src/test/java/io/trino/sql/query/TestDistinctWithOrderBy.java
index 68b7447f8fd..867142211fc 100644
--- a/core/trino-main/src/test/java/io/trino/sql/query/TestDistinctWithOrderBy.java
+++ b/core/trino-main/src/test/java/io/trino/sql/query/TestDistinctWithOrderBy.java
@@ -72,6 +72,9 @@ public class TestDistinctWithOrderBy
         assertThat(assertions.query("SELECT DISTINCT a, b a FROM (VALUES (2, 10), (1, 20), (2, 10)) T(a, b) ORDER BY T.a"))
                 .ordered()
                 .matches("VALUES (1, 20), (2, 10)");
+
+        assertThat(assertions.query("SELECT DISTINCT a as \"x\" FROM (VALUES 2, 1, 2) t(a) ORDER BY X"))
+            .matches("VALUES 1, 2");
     }
 
     @Test

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions