diff --git a/core/src/main/java/org/apache/calcite/sql/validate/SqlValidatorImpl.java b/core/src/main/java/org/apache/calcite/sql/validate/SqlValidatorImpl.java index 02a044820f4..691fafcd1bc 100644 --- a/core/src/main/java/org/apache/calcite/sql/validate/SqlValidatorImpl.java +++ b/core/src/main/java/org/apache/calcite/sql/validate/SqlValidatorImpl.java @@ -5320,6 +5320,12 @@ protected void rewriteOrderByAll(SqlSelect select) { throw newValidationError(expr, RESOURCE.orderByAllRequiresExplicitSelectList()); } + // A constant literal is a no-op sort key (nothing to reorder); excluding it also + // avoids materializing an ambiguous "ORDER BY " on unparse, which + // would be re-parsed as an ordinal position. + if (expr instanceof SqlLiteral) { + continue; + } keys.add(applyOrderByAllDirection(expr, desc, nulls, pos)); } select.setOrderBy(new SqlNodeList(keys, pos)); @@ -5521,7 +5527,10 @@ private void rewriteGroupByAll(SqlSelect select) { throw newValidationError(expr, RESOURCE.groupByAllRequiresExplicitSelectList()); } - if (aggOrOverFinder.findAgg(expr) == null) { + // A constant literal is a no-op grouping key (one group either way); excluding it + // also avoids materializing an ambiguous "GROUP BY " on unparse, + // which would be re-parsed as an ordinal position. + if (aggOrOverFinder.findAgg(expr) == null && !(expr instanceof SqlLiteral)) { keys.add(expr); } } diff --git a/core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java b/core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java index 7bfc58eafe6..cf3359ddaa0 100644 --- a/core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java +++ b/core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java @@ -7367,6 +7367,13 @@ public boolean isBangEqualAllowed() { .withValidatorIdentifierExpansion(true) .withConformance(SqlConformanceEnum.BABEL) .ok(); + + // A constant literal is a no-op sort key and is excluded: only SAL is a + // sort key, so the rewrite does not emit an ambiguous "ORDER BY 42". + sql("select sal, 42 from emp order by all") + .rewritesTo("SELECT `SAL`, 42\n" + + "FROM `EMP`\n" + + "ORDER BY `SAL`"); } @Test void testOrder() { @@ -7829,6 +7836,13 @@ public boolean isBangEqualAllowed() { sql("select deptno as d, count(*) from emp group by all") .withConformance(SqlConformanceEnum.LENIENT) .ok(); + + // A constant literal is a no-op grouping key and is excluded: only DEPTNO + // becomes a key, so the rewrite does not emit an ambiguous "GROUP BY 42". + sql("select deptno, 42 from emp group by all") + .rewritesTo("SELECT `DEPTNO`, 42\n" + + "FROM `EMP`\n" + + "GROUP BY `EMP`.`DEPTNO`"); } /** Test case for