Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
25455: opt/optbuilder: Fix bug with ORDER BY and aggregate alias r=rytaft a=rytaft

This commit fixes a bug in which ordering by an alias of
an aggregate causes an error.

Queries such as:
`SELECT SUM(a) AS a2 FROM abcd GROUP BY c ORDER BY a2`

were incorrectly causing the error:
`error: column "a2" must appear in the GROUP BY clause or be
used in an aggregate function`

This commit fixes that issue, so now the query builds successfully.

Release note: None

Co-authored-by: Rebecca Taft <[email protected]>
  • Loading branch information
craig[bot] and rytaft committed May 13, 2018
2 parents c63ec54 + 75d6ea5 commit bb2a4fd
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 1 deletion.
2 changes: 1 addition & 1 deletion pkg/sql/opt/optbuilder/scope.go
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,7 @@ func (s *scope) findExistingCol(expr tree.TypedExpr) *scopeColumn {
exprStr := symbolicExprStr(expr)
for i := range s.cols {
col := &s.cols[i]
if exprStr == col.getExprStr() {
if expr == col || exprStr == col.getExprStr() {
return col
}
}
Expand Down
49 changes: 49 additions & 0 deletions pkg/sql/opt/optbuilder/testdata/aggregate
Original file line number Diff line number Diff line change
Expand Up @@ -2698,3 +2698,52 @@ build
SELECT SUM(abc.d) FILTER (WHERE abc.d > 0) FROM abc
----
error: aggregates with FILTER are not supported yet

# Check that ordering by an alias of an aggregate works.
build
SELECT MAX(k) AS mk FROM kv GROUP BY v ORDER BY mk
----
sort
├── columns: mk:5(int)
├── ordering: +5
└── project
├── columns: mk:5(int)
├── group-by
│ ├── columns: kv.v:2(int) mk:5(int)
│ ├── grouping columns: kv.v:2(int)
│ ├── project
│ │ ├── columns: kv.v:2(int) kv.k:1(int!null)
│ │ ├── scan kv
│ │ │ └── columns: kv.k:1(int!null) kv.v:2(int) kv.w:3(int) kv.s:4(string)
│ │ └── projections
│ │ ├── variable: kv.v [type=int]
│ │ └── variable: kv.k [type=int]
│ └── aggregations
│ └── max [type=int]
│ └── variable: kv.k [type=int]
└── projections
└── variable: mk [type=int]

build
SELECT MAX(k) AS mk FROM kv GROUP BY v ORDER BY MAX(k)
----
sort
├── columns: mk:5(int)
├── ordering: +5
└── project
├── columns: mk:5(int)
├── group-by
│ ├── columns: kv.v:2(int) mk:5(int)
│ ├── grouping columns: kv.v:2(int)
│ ├── project
│ │ ├── columns: kv.v:2(int) kv.k:1(int!null)
│ │ ├── scan kv
│ │ │ └── columns: kv.k:1(int!null) kv.v:2(int) kv.w:3(int) kv.s:4(string)
│ │ └── projections
│ │ ├── variable: kv.v [type=int]
│ │ └── variable: kv.k [type=int]
│ └── aggregations
│ └── max [type=int]
│ └── variable: kv.k [type=int]
└── projections
└── variable: mk [type=int]

0 comments on commit bb2a4fd

Please sign in to comment.