go-mysql-server
go-mysql-server copied to clipboard
Sort nodes above Window/Group By Aggregations
We appear to push Sort
nodes belowGroupBy
and Window
in some cases. In general window functions are responsible for sorting the input buffer once for partitioning, and then a second time for restoring the original sort order.
tmp3> create table mytable (a int primary key, i varchar(20));
tmp3> explain SELECT COUNT(*) c, i AS foo FROM mytable GROUP BY i ORDER BY i DESC;
+---------------------------------------------------+
| plan |
+---------------------------------------------------+
| Project(COUNT(*) as c, foo) |
| └─ GroupBy |
| ├─ SelectedExprs(COUNT(*), mytable.i as foo) |
| ├─ Grouping(mytable.i) |
| └─ Sort(mytable.i DESC) |
| └─ Projected table access on [i] |
| └─ Exchange(parallelism=12) |
| └─ Table(mytable) |
+---------------------------------------------------+
We should preserve this behavior in the analyzer when the grouping/partitioning scheme matches the sort order, but otherwise Sort
should live above GroupBy
.