Skip to content

Sort by an expression of the GROUP BY key to close #2817 - #2999

Open
mateuscmtropical wants to merge 2 commits into
AlaSQL:developfrom
mateuscmtropical:fix-2817-order-by-group-func
Open

mateuscmtropical wants to merge 2 commits into
AlaSQL:developfrom
mateuscmtropical:fix-2817-order-by-group-func

Conversation

@mateuscmtropical

@mateuscmtropical mateuscmtropical commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Closes #2817

What was wrong

In a grouped query, an ORDER BY key that is not a column was compiled with v.toJS('g', ''). For ORDER BY LOWER(c) that reads g['c'], which the group row does not have. Every key was empty, so the rows kept their insertion order.

What changed

compileSelectGroup2 collects the GROUP BY expressions that are not bare columns, including the ones inside ROLLUP, CUBE and GROUPING SETS. When an ORDER BY expression is one of them, like LOWER(c) after GROUP BY LOWER(c), it reads the value the group row already has. Any other expression, like a*2 after GROUP BY a, is computed from the key columns as before.

Tests

test/test2817.js covers ORDER BY the key expression with an alias, without an alias and DESC, with HAVING, ORDER BY the alias, an operator expression (a % 2), and expressions that are not GROUP BY keys (a*2, a+b and UPPER(c)). The first three fail on develop.

yarn test-only gives 2559 pass. The only failures are the 5 Test 418 cases that load files from the internet.

@mathiasrw

Copy link
Copy Markdown
Member

Thanks, ORDER BY LOWER(c) after GROUP BY LOWER(c) now sorts, and so does ORDER BY a % 2.

query.groupColumns also holds SELECT expressions without an alias, and the group row doesn't carry their values. So this PR breaks the following SQL

SELECT a, a*2 FROM th GROUP BY a ORDER BY a*2 DESC
SELECT a, b, a+b FROM th GROUP BY a, b ORDER BY a+b
SELECT c, UPPER(c) FROM th GROUP BY c ORDER BY UPPER(c) DESC

Maybe limit the lookup to the GROUP BY keys, and add these three as tests cases?

@mateuscmtropical

Copy link
Copy Markdown
Contributor Author

Done. The lookup now reads from the group row only the expressions that are GROUP BY keys. Anything else is computed from the key columns as before. Your three queries are tests F, G and H in test2817.js, and they failed on the previous commit.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ORDER BY LOWER(c) in a query grouped by LOWER(c) does not sort

2 participants