From 75d6ea57e84f400913c2121b724df6e0c08b48bc Mon Sep 17 00:00:00 2001 From: Rebecca Taft Date: Sun, 13 May 2018 13:14:58 -0400 Subject: [PATCH] opt/optbuilder: Fix bug with ORDER BY and aggregate alias 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 --- pkg/sql/opt/optbuilder/scope.go | 2 +- pkg/sql/opt/optbuilder/testdata/aggregate | 49 +++++++++++++++++++++++ 2 files changed, 50 insertions(+), 1 deletion(-) diff --git a/pkg/sql/opt/optbuilder/scope.go b/pkg/sql/opt/optbuilder/scope.go index a70aea1b64b1..dd8c464df9b6 100644 --- a/pkg/sql/opt/optbuilder/scope.go +++ b/pkg/sql/opt/optbuilder/scope.go @@ -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 } } diff --git a/pkg/sql/opt/optbuilder/testdata/aggregate b/pkg/sql/opt/optbuilder/testdata/aggregate index 01cfb0cf21d5..6665be9e8ad9 100644 --- a/pkg/sql/opt/optbuilder/testdata/aggregate +++ b/pkg/sql/opt/optbuilder/testdata/aggregate @@ -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]