Skip to content

fix(optimizer): don't expand aggregate aliases into GROUP BY - #7971

Open
fivetran-kwoodbeck wants to merge 3 commits into
mainfrom
optimizer/fix-qualify-group-by-alias-collision
Open

fix(optimizer): don't expand aggregate aliases into GROUP BY#7971
fivetran-kwoodbeck wants to merge 3 commits into
mainfrom
optimizer/fix-qualify-group-by-alias-collision

Conversation

@fivetran-kwoodbeck

Copy link
Copy Markdown
Collaborator

qualify_columns can replace a GROUP BY reference with an aggregate alias's definition, nesting an aggregate inside GROUP BY which gives invalid SQL and is also non idempotent. Fixed by ensuring aggregate alias is never expanded when is_group_by.

Sample input:

SELECT MAX(x) AS x FROM a AS a JOIN b AS b ON a.id = b.id GROUP BY UPPER(x)

Previous output:

SELECT MAX(x) AS x FROM a AS a JOIN b AS b ON a.id = b.id GROUP BY UPPER(MAX(x))

Note: GROUP BY UPPER(x) became GROUP BY UPPER(MAX(x)) which is wrong.

Output after Patch:

SELECT MAX(x) AS x FROM a AS a JOIN b AS b ON a.id = b.id GROUP BY UPPER(x)

@github-actions

github-actions Bot commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

SQLGlot Integration Test Results

✅ All tests passed

Comparing:

  • this branch (sqlglot:optimizer/fix-qualify-group-by-alias-collision @ sqlglot 597f605)
  • baseline (main @ sqlglot feec46e)

Overall

main: 192414 total, 153558 passed (pass rate: 79.8%)

sqlglot:optimizer/fix-qualify-group-by-alias-collision: 180220 total, 142406 passed (pass rate: 79.0%)

Transitions:
No change

Dialect pair changes: 0 previous results not found, 3 current results not found

✅ All tests passed

@fivetran-kwoodbeck
fivetran-kwoodbeck force-pushed the optimizer/fix-qualify-group-by-alias-collision branch from 56d0f7b to ec7c86e Compare July 27, 2026 17:00
Comment thread sqlglot/optimizer/qualify_columns.py
@fivetran-kwoodbeck
fivetran-kwoodbeck force-pushed the optimizer/fix-qualify-group-by-alias-collision branch from ec7c86e to e4f732f Compare July 28, 2026 14:39
@fivetran-kwoodbeck
fivetran-kwoodbeck force-pushed the optimizer/fix-qualify-group-by-alias-collision branch from 64d2385 to 07f7ae5 Compare July 28, 2026 16:38
@fivetran-kwoodbeck
fivetran-kwoodbeck force-pushed the optimizer/fix-qualify-group-by-alias-collision branch from 07f7ae5 to 14e8554 Compare July 28, 2026 18:28
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.

2 participants