Skip to content

fix(optimizer)!: don't fan out EXISTS decorrelation over grouped subqueries - #8318

Merged
georgesittas merged 2 commits into
mainfrom
jo/exists_group_by_decorrelation
Sep 8, 2026
Merged

fix(optimizer)!: don't fan out EXISTS decorrelation over grouped subqueries#8318
georgesittas merged 2 commits into
mainfrom
jo/exists_group_by_decorrelation

Conversation

@georgesittas

Copy link
Copy Markdown
Collaborator

Unnesting an EXISTS subquery with its own GROUP BY appended the join key to the existing grouping, so the derived table was no longer unique on it and the LEFT JOIN emitted one outer row per group. A plain GROUP BY, DISTINCT or ORDER BY can't change whether the subquery returns rows (we already bail earlier for ORDER BY + LIMIT), so they're dropped before decorrelating. Since HAVING and QUALIFY do filter the groups, and grouping sets yield a row even on empty input, those subqueries are no longer unnested.

See also: #8317 (comment).

Comment thread sqlglot/optimizer/unnest_subqueries.py
@github-actions

github-actions Bot commented Sep 8, 2026

Copy link
Copy Markdown
Contributor

SQLGlot Integration Test Results

✅ All tests passed

Comparing:

  • this branch (sqlglot:jo/exists_group_by_decorrelation @ sqlglot 276e4fb)
  • baseline (main @ sqlglot 1d753d7)

Overall

main: 182937 total, 163862 passed (pass rate: 89.6%)

sqlglot:jo/exists_group_by_decorrelation: 170743 total, 152710 passed (pass rate: 89.4%)

Transitions:
No change

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

✅ All tests passed

…ueries

Unnesting an EXISTS subquery with its own GROUP BY appended the join key to the existing grouping, so the derived table was no longer unique on it and the LEFT JOIN emitted one outer row per group. A plain GROUP BY, DISTINCT or ORDER BY can't change whether the subquery returns rows (we already bail earlier for ORDER BY + LIMIT), so they're dropped before decorrelating. Since HAVING and QUALIFY do filter the groups, and grouping sets yield a row even on empty input, those subqueries are no longer unnested.

See also: #8317 (comment).
@georgesittas
georgesittas force-pushed the jo/exists_group_by_decorrelation branch from 87962f9 to 79b1e16 Compare September 8, 2026 15:52
@georgesittas
georgesittas merged commit 0d88a21 into main Sep 8, 2026
8 checks passed
@georgesittas
georgesittas deleted the jo/exists_group_by_decorrelation branch September 8, 2026 16:07
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