Skip to main content

simplify_from_less_existence_subqueries

Function simplify_from_less_existence_subqueries 

Source
pub fn simplify_from_less_existence_subqueries(
    expr: &mut HirRelationExpr,
) -> Result<(), RecursionLimitError>
Expand description

Collapses EXISTS over a FROM-less subquery into an equivalent scalar predicate on the outer row, so that decorrelation produces a plain Filter rather than a semijoin (for EXISTS) or an antijoin (for NOT EXISTS).

A FROM-less subquery is a chain of Map, Project, and Filter nodes over a single-row Constant (the join identity of a query with no FROM clause). Such a subquery yields exactly one row when every Filter predicate is TRUE and zero rows otherwise, so

EXISTS(<from-less subquery with predicates p1, p2, ...>) == (p1 AND p2 AND ...) IS TRUE

evaluated on the outer row. The IS TRUE is mandatory for null safety. An empty subquery (some predicate FALSE or NULL) must make EXISTS return FALSE, which IS TRUE reproduces while a bare predicate would leak NULL. NOT EXISTS then becomes NOT ((...) IS TRUE), which is ... IS NOT TRUE and likewise null-safe.

The rewrite fires only on correlated subqueries, where the predicate references at least one outer column. This keeps it to the pure existence check that a genuine anti/semi-join would otherwise be lowered to, and it avoids changing whether an uncorrelated erroring subquery is evaluated when the outer relation is empty.

This closes database-issues#2613 (x IN (SELECT ... WHERE p), which try_simplify_quantified_comparisons has already turned into an EXISTS) and database-issues#2969 (NOT EXISTS (SELECT ... WHERE p)). It must run after try_simplify_quantified_comparisons.