Skip to content

fix: decorrelate EXISTS with non-equality predicates below HAVING - #27790

Open
SeaKurisu wants to merge 1 commit into
apache:mainfrom
SeaKurisu:fix/27764-correlated-exists-having
Open

SeaKurisu wants to merge 1 commit into
apache:mainfrom
SeaKurisu:fix/27764-correlated-exists-having

Conversation

@SeaKurisu

Copy link
Copy Markdown

Which issue does this PR close?

Closes #27764.

Rationale for this change

A correlated range predicate can match several different inner keys for one outer row. For example, when the outer key is 1, both 2 and 3 contribute to COUNT(*). Evaluating HAVING separately for each inner key would change that count. The existing optimizer leaves this subquery correlated, and physical planning fails.

What changes are included in this PR?

Add a fallback for correlated EXISTS over an ungrouped aggregate with HAVING. It materializes the outer input once, joins each distinct tuple of outer correlation values to its matching inner rows, and evaluates the aggregate and HAVING per tuple. A marker excludes the synthetic row from an unmatched left join, so COUNT(*) still sees zero input rows. A null-safe join maps the passing tuples back to the original outer rows, preserving duplicates.

The fallback skips volatile expressions and nested subqueries. Its cost depends on the number of distinct outer tuples and the number of matching inner rows.

What is the testing strategy for this PR?

Six SQL regression cases in subquery_decorrelation.slt cover the reported EXISTS and NOT EXISTS queries, duplicate outer rows, NULL keys, empty aggregate input, and an aggregate filter with two correlated bounds. Local formatting, all-target/all-feature Clippy, and the extended workspace test suite passed.

Are there any user-facing changes?

Yes. The example in #27764 now returns 1 and 2 for EXISTS and 3 for NOT EXISTS.

@github-actions github-actions Bot added optimizer Optimizer rules sqllogictest SQL Logic Tests (.slt) labels Nov 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

optimizer Optimizer rules sqllogictest SQL Logic Tests (.slt)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Correlated EXISTS with a non-equality condition and HAVING fails to plan

1 participant