Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -730,6 +730,11 @@ class Analyzer(
}
Sort(newOrders, global, child)

// Eliminate the useless position numbers
case s @ Sort(orders, global, child)
if !conf.orderByOrdinal && orders.exists(o => IntegerIndex.unapply(o.child).nonEmpty) =>
Sort(orders.filterNot(o => IntegerIndex.unapply(o.child).nonEmpty), global, child)

// Replace the index with the corresponding expression in aggregateExpressions. The index is
// a 1-base position of aggregateExpressions, which is output columns (select expression)
case a @ Aggregate(groups, aggs, child)
Expand Down Expand Up @@ -1252,7 +1257,9 @@ class Analyzer(
case ae: AnalysisException => filter
}

case sort @ Sort(sortOrder, global, aggregate: Aggregate) if aggregate.resolved =>
// If there exists ordinal sort orders, it's not resolved completely yet. See SPARK-16955.
case sort @ Sort(sortOrder, global, aggregate: Aggregate) if aggregate.resolved &&
sortOrder.forall(x => IntegerIndex.unapply(x.child).isEmpty) =>

// Try resolving the ordering as though it is in the aggregate clause.
try {
Expand Down
13 changes: 13 additions & 0 deletions sql/core/src/test/scala/org/apache/spark/sql/SQLQuerySuite.scala
Original file line number Diff line number Diff line change
Expand Up @@ -495,6 +495,19 @@ class SQLQuerySuite extends QueryTest with SharedSQLContext {
)
}

test("SPARK-16955: Using ordinals in ORDER BY and GROUP BY causes an analysis error") {
withSQLConf(SQLConf.ORDER_BY_ORDINAL.key -> "true") {
checkAnswer(
sql("SELECT a, avg(a) FROM (SELECT * FROM VALUES 1,2,3 T(a)) U GROUP BY 1 ORDER BY 1 DESC"),
sql("SELECT a, avg(a) FROM (SELECT * FROM VALUES 1,2,3 T(a)) U GROUP BY a ORDER BY a DESC"))
}
withSQLConf(SQLConf.ORDER_BY_ORDINAL.key -> "false") {
checkAnswer(
sql("SELECT a, avg(a) FROM (SELECT * FROM VALUES 1,2,3 T(a)) U GROUP BY 1 ORDER BY 1 DESC"),
sql("SELECT a, avg(a) FROM (SELECT * FROM VALUES 1,2,3 T(a)) U GROUP BY a"))
}
}

test("select *") {
checkAnswer(
sql("SELECT * FROM testData"),
Expand Down