Skip to content

Fix vacuous truth for x op ALL (empty subquery) - #106373

Draft
mohhddhassan wants to merge 34 commits into
ClickHouse:masterfrom
mohhddhassan:fix-all-empty-subquery-vacuous-truth
Draft

mohhddhassan wants to merge 34 commits into
ClickHouse:masterfrom
mohhddhassan:fix-all-empty-subquery-vacuous-truth

Conversation

@mohhddhassan

@mohhddhassan mohhddhassan commented Jun 3, 2026 •

Copy link
Copy Markdown
Contributor

x op ALL (empty set) should return TRUE per SQL standard (vacuous truth).

ClickHouse was returning FALSE because the = ALL rewrite uses singleValueOrNull,
which returns NULL for empty sets, making x IN (NULL) = FALSE incorrectly. The
min / max rewrites used for the other comparison operators have the same problem,
because they return the default value of the type for an empty set.

Fixed in modifyAST by also computing whether the right-hand side is empty. The emptiness flag and the
aggregate are computed by a single scalar subquery SQ = (SELECT (count(*) = 0, aggregate(*)) FROM S) returning a
tuple. SQ occurs once in the rewritten expression, under an alias derived from a hash of the aggregate function name and the subquery text (not IAST::getTreeHash, which would keep every updateTreeHashImpl in the WebAssembly parser build), and other places refer
to it by that alias. The left-hand side x also occurs once. So the right-hand side is evaluated once (observable when it is non-deterministic) and the
parsed query stays linear in the nesting depth of ALL quantifiers, on both sides:

x < ALL (S)  --> ifNull(tupleElement(SQ AS _a, 1), 1) OR x < tupleElement(_a, 2)     (SQ uses min; the same for <=)
x > ALL (S)  --> ifNull(tupleElement(SQ AS _a, 1), 1) OR x > tupleElement(_a, 2)     (SQ uses max; the same for >=)
x = ALL (S)  --> ifNull(tupleElement(SQ AS _a, 1), 1) OR x IN (SELECT tupleElement(_a, 2))     (SQ uses singleValueOrNull)

A NULL scalar is treated as an empty right-hand side. This happens when the
aggregation produces no row: with empty_result_for_aggregation_by_empty_set = 1, or for a missing group of a
correlated subquery.

For a non-empty right-hand side the results are unchanged. For <, <=, >, >= ALL, x is compared with a
constant after the scalar subquery is evaluated, so the primary key is still used. For = ALL the rewrite is the former
x IN (SELECT singleValueOrNull(*) FROM S), only the single row of the IN subquery takes its value from SQ
instead of computing it again. So everything IN with a subquery does is kept: the set comparison of tuples
((1, NULL) = ALL (SELECT (1, NULL)) is 1), a NULL x following transform_null_in, FALSE rather than NULL when
the subquery returns a NULL or several distinct values, conversions ('01' = ALL (SELECT 1) is 1), the UInt8
result type for a non-nullable x, and the use of the primary key, also a Nullable one
(id = ALL (SELECT 12345) reads one granule). As on master, a correlated subquery is not supported in = ALL
(IN does not support it); it is supported for the other operators. In a distributed query the right-hand side
is evaluated once, on the initiator. The operator documentation is updated accordingly.

Tests: 04759_all_subquery_single_evaluation fails if the right-hand side is evaluated twice.
05448_all_subquery_missing_row_and_nesting covers the missing aggregate row, correlated subqueries and quantifiers nested in the right-hand and in the left-hand side. 05493_all_subquery_primary_key_and_conversions covers primary key usage (also with allow_nullable_key) and conversions. 05621_equals_all_transform_null_in_and_result_type checks that = ALL keeps the transform_null_in behaviour, the comparison of tuples and the result type of the former IN rewrite.

Scope: the fix covers the aggregate-based rewrites, that is = ALL, < ALL, <= ALL,
> ALL and >= ALL. != ALL is deliberately left as a plain notIn, which already
returns TRUE on an empty right-hand side for a non-NULL left-hand side; only
NULL != ALL (empty subquery) keeps returning NULL, following the NULL semantics of
notIn and mirroring the untouched NULL = ANY (empty subquery): under the default
transform_null_in = 0 a NULL left-hand side (a literal NULL, a constant of a Nullable
type, or a NULL value inside a Nullable column) yields NULL before the emptiness of the
set is looked at, and only transform_null_in = 1 makes an empty right-hand side TRUE
for NULL as well. Making the empty-set NULL semantics standard-conforming belongs in
Set / FunctionIn, not in the parser rewrite, and is a separate decision.
05045_notequals_all_single_evaluation pins that shape, so the != ALL right-hand side
also stays evaluated exactly once, and pins the NULL results above.

Closes #105957

Changelog category :

  • Bug Fix (user-visible misbehavior in an official stable release)

Changelog entry (a user-readable short description):

Fixed = ALL, < ALL, <= ALL, > ALL and >= ALL on an empty subquery incorrectly returning FALSE instead of TRUE (vacuous truth). NULL != ALL (empty subquery) still follows the existing notIn NULL semantics.


Workflow [PR]
Sync PR [sync-upstream/pr/106373]

x op ALL (empty set) should return TRUE per SQL standard.
The singleValueOrNull rewrite returned NULL for empty sets,
making x IN (NULL) = FALSE incorrectly.

Fix by wrapping the rewrite as:
  (SELECT count() FROM subquery) = 0 OR x IN (singleValueOrNull subquery)

Fixes ClickHouse#105957
@qoega qoega added the can be tested Allows running workflows for external contributors label Jun 6, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [59c9fbc]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py FAIL

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 6, 2026
Comment thread src/Parsers/ExpressionListParsers.cpp Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member

Duplicating the subquery looks risky.

@alexey-milovidov

Copy link
Copy Markdown
Member

When it contains non-deterministic functions.

@alexey-milovidov alexey-milovidov added st-discussion When the implementation aspects are not clear or when the PR is on hold due to questions. close in a month if not active This will be closed in case of no information labels Jun 7, 2026
@alexey-milovidov
alexey-milovidov marked this pull request as draft June 9, 2026 02:39
@mohhddhassan

Copy link
Copy Markdown
Contributor Author

@alexey-milovidov, I used subquery_node->clone() to duplicate the subquery, one copy for count() to detect the empty case, and another for singleValueOrNull(*) and yeah your correct this is risky when the subquery contains non-deterministic functions like rand() since both executions may return different results.

So would it be better to avoid duplication entirely by introducing a new aggregate function that can distinguish between an empty set and a multi-value set returning a sentinel value for empty instead of NULL? That way the subquery only runs once.

Happy to rework the approach based on your guidance.

Comment thread src/Parsers/ExpressionListParsers.cpp Resolved
alexey-milovidov and others added 4 commits July 2, 2026 22:14
The vacuous-truth change altered the early-return condition in `modifyAST`
from `(type == ANY && function_equals)` to `type == ANY`, which made
`x != ANY (subquery)` and `x != SOME (subquery)` rewrite to a plain `notIn`
instead of `notIn (SELECT singleValueOrNull(*) FROM subquery)`.

That broke the semantics: `x != ANY (S)` must be TRUE when some element of
`S` differs from `x`, but plain `x NOT IN S` only tests set membership. For
example `SELECT 1 != ANY (SELECT number FROM numbers(10))` returned `0`
instead of `1`, failing `02007_test_any_all_operators` and `04042_some_keyword`.

Restore the original condition so `= ANY` and `!= ALL` still early-return as
`in`/`notIn`, while `= ALL` and `!= ANY` continue to the `singleValueOrNull`
rewrite. The vacuous-truth `ALL` wrapping is unaffected and still applies to
`= ALL`, `>= ALL`, `> ALL`, `<= ALL`, `< ALL`.

Fixes the Fast test failures at
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=106373&sha=614d7555da0d6593743fb2385e38c70f0c100d68&name_0=PR&name_1=Fast%20test

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.20% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 78.40% 78.40% +0.00%

Changed lines: Changed C/C++ lines covered: 36/36 (100.00%) · Uncovered code

Full report · Diff report

The vacuous-truth fix for `x op ALL (subquery)` used to `clone` the
right-hand side and build the `count` emptiness check from the copy, so
the subquery was executed twice. For a non-deterministic right-hand side
the two executions can disagree, and the rewrite could return a result
that no single evaluation could produce: with the old rewrite,
`SELECT 1 = ALL (SELECT 1 FROM numbers(1) WHERE rand() % 2 = 0)`
returned the wrong answer `0` in 48 out of 200 runs, because the `count`
branch saw a row while the `singleValueOrNull` branch saw none.

Instead of two different subqueries, `count` and the aggregate are now
computed by a single `SELECT` producing a tuple, and the two values are
taken apart with `tupleElement`:

    x op ALL (S) -->
        tupleElement(SQ, 1) = 0 OR x op tupleElement(SQ, 2)
        where SQ = (SELECT (count(*), aggregate_function(*)) FROM S)

Both occurrences of `SQ` are textually identical, and scalar subqueries
are cached by the hash of the subquery - `ExecuteScalarSubqueriesVisitor`
for the old analyzer and `evaluateScalarSubqueryIfNeeded` for the new one
- so `S` is evaluated exactly once and both `tupleElement` calls observe
the same evaluation. This is visible in `ProfileEvents` for
`SELECT 1 = ALL (SELECT number FROM numbers(1000000))`:
`ScalarSubqueriesCacheMiss: 1`, `ScalarSubqueriesGlobalCacheHit: 1` and
`SelectedRows: 1000001` - one scan, not two.

The rewrite keeps the `in` / `notIn` and `min` / `max` shapes, so the
result for a non-empty right-hand side is unchanged, with both analyzers.

Added a regression test that would fail if the right-hand side is cloned
again, as requested in the review.
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 While verifying the ALL rewrite I noticed the mirror-image problem in ANY, which this PR deliberately leaves alone (it is out of the scope of #105957) — recording it here so the scope is a conscious choice:

SELECT 1 != ANY (SELECT 1 WHERE 0); -- returns 1, should be 0
SELECT 1 >= ANY (SELECT 1 WHERE 0); -- returns 1, should be 0
SELECT 1 =  ANY (SELECT 1 WHERE 0); -- returns 0, correct

x op ANY (empty set) is FALSE (there is no witness row), which is the dual of vacuous truth for ALL. = ANY is already correct because it rewrites to a plain IN over an empty set, but != ANY rewrites to notIn (SELECT singleValueOrNull(*) ...) → x notIn (NULL) → 1, and >= ANY / > ANY / <= ANY / < ANY rewrite to a comparison against min / max, which return the default value of the type for an empty set.

The same count-in-a-tuple trick would fix it (the disjunct becomes a conjunct: tupleElement(SQ, 1) != 0 AND x op tupleElement(SQ, 2)), but it changes the result of more queries than #105957 asks for, so it should be a separate decision. Happy to do it here or in a follow-up PR, whichever you prefer.

Comment thread src/Parsers/ExpressionListParsers.cpp Resolved
@abashkeev abashkeev added the comp-sql-syntax SQL/grammar parsing, AST nodes, syntax-level features. label Sep 4, 2026
…rite fixes

The comment claimed `x op ALL (empty set)` is TRUE for every operator, but
`!= ALL` returns early as a plain `notIn`, so `NULL != ALL (empty subquery)`
still returns NULL. State the covered operators explicitly and document the
`!= ALL` NULL case. The PR description and changelog entry were narrowed the
same way.
alexey-milovidov and others added 2 commits September 17, 2026 01:15
…p the old-analyzer mention

The review asked to either prove or fix the claim that `NULL != ALL (empty subquery)` returns NULL:
the empty-set shortcut in `FunctionIn` returns a constant `1` for `notIn`, so it looked like NULL
could never come out. It does: under the default `transform_null_in = 0` the NULL left-hand side is
handled by the default implementation for nulls before the set is looked at, so a literal NULL, a
constant of a Nullable type and a NULL value inside a Nullable column all give NULL. Only
`transform_null_in = 1` turns an empty right-hand side into TRUE for NULL as well. These cases are
now pinned in `05045_notequals_all_single_evaluation`, together with the contrasting
`NULL = ALL (empty subquery)` = 1 of the aggregate-based rewrite, and the comment in `modifyAST`
spells the rule out.

The comment also referred to `ExecuteScalarSubqueriesVisitor` for `enable_analyzer = 0`. That path is
gone: the analyzer is mandatory since 26.9 and `enable_analyzer = 0` is rejected, so the only scalar
subquery cache is the one in `evaluateScalarSubqueryIfNeeded`, and no paired old-analyzer run of
`04759_all_subquery_single_evaluation` is possible.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Comment thread src/Parsers/ExpressionListParsers.cpp Resolved
alexey-milovidov and others added 3 commits September 26, 2026 02:49
Address review: the emptiness check needed for vacuous truth and the
compared value must come from one evaluation of the right-hand side, which
an `IN` set cannot carry; document the resulting distributed behaviour.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Parsers/ExpressionListParsers.cpp Resolved
alexey-milovidov and others added 2 commits October 10, 2026 08:33
The operator docs and the banner comment of `modifyAST` still described
`a = ALL (subquery)` as `a IN (SELECT singleValueOrNull(*) FROM subquery)`.
Describe the actual rewrite, the evaluation on the initiator in distributed
queries, and the vacuous truth for an empty subquery.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread docs/reference/operators/index.mdx Resolved
…arison

The `= ALL` rewrite still compares with `in`, not `equals`, against
`tupleElement(SQ, 2)`. This is intentional: when the subquery returns a NULL
or several distinct values, `singleValueOrNull` gives NULL, and `x IN NULL`
is 0 as before, while `x = NULL` would be NULL. Fix the comment and the docs
that described it as `=`, and add a regression test pinning this.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Parsers/ExpressionListParsers.cpp Resolved
Comment thread src/Parsers/ExpressionListParsers.cpp Resolved
alexey-milovidov and others added 2 commits October 25, 2026 03:54
… a missing aggregate row as empty

The previous rewrite referenced the scalar subquery `(SELECT (count(*), agg(*)) FROM subquery)` twice. Nested
`ALL` quantifiers then duplicated the already rewritten inner expressions on every level, so the query grew
exponentially with the nesting depth (30 nested `1 = ALL (...)` took a minute and failed with "Query tree is too
big"). Now each operand occurs exactly once:

- `<`, `<=`, `>`, `>= ALL` use a lexicographic tuple comparison, `(0, x) < ifNull(SQ, (1, NULL))` where
  `SQ = (SELECT (count(*) = 0, min(*)) FROM subquery)`, and symmetrically for `>` with `max`. The first elements
  differ exactly when the right-hand side is empty, which makes the result TRUE.
- `= ALL` takes the tuple apart inside a lambda:
  `arrayMap((_rhs, _lhs) -> ifNull(tupleElement(_rhs, 1), 1) OR _lhs IN tupleElement(_rhs, 2), [SQ], [x])[1]`.

A missing aggregate row (`empty_result_for_aggregation_by_empty_set = 1`, or a correlated subquery for a missing
group) makes the scalar subquery NULL; it is now recognized as an empty right-hand side.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@mintlify

mintlify Bot commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

Preview approval required

This pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit 59c9fbc.

Approve preview

Comment thread src/Parsers/ExpressionListParsers.cpp Resolved
Comment thread src/Parsers/ExpressionListParsers.cpp Resolved
@maxknv maxknv added the external Author is not a member of the ClickHouse organization label Nov 2, 2026
alexey-milovidov and others added 2 commits November 3, 2026 11:09
…y key and conversions

The previous rewrite of `x = ALL (subquery)` passed the scalar subquery and `x` through
`arrayMap` with a lambda, and `x < ALL` etc. compared tuples `(flag, x)`. Neither is visible
to the primary key analysis, so selective `ALL` filters scanned the whole table, and inside the
lambda `in` was not a comparison with a constant, so `'01' = ALL (SELECT 1)` became 0.

Now the scalar subquery `SQ = (SELECT (count(*) = 0, aggregate(*)) FROM subquery)` occurs once,
under an alias derived from its hash, and is referenced by that alias:

    x op ALL S --> ifNull(tupleElement(SQ AS _a, 1), 1) OR x op tupleElement(_a, 2)
    x =  ALL S --> ifNull(tupleElement(SQ AS _a, 1), 1)
                   OR (x = tupleElement(_a, 2) AND isNotNull(tupleElement(_a, 2)))

`x` is compared with a constant, so the primary key is used and the conversions are those of a
comparison with a constant. The right-hand side is still evaluated once, and the parsed query
stays linear in the nesting depth.

Also reduce the nesting depth in `05448_all_subquery_missing_row_and_nesting`: 30 levels of
nested subqueries exceeded the stack under TSan (`TOO_DEEP_RECURSION`).
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=106373&sha=latest&name_0=PR&name_1=Stateless%20tests%20%28amd_tsan%2C%20flaky%20check%29
PR: ClickHouse#106373

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Parsers/ExpressionListParsers.cpp Resolved
Comment thread src/Parsers/ExpressionListParsers.cpp Resolved
alexey-milovidov and others added 2 commits November 11, 2026 21:56
…LL`; drop `getTreeHash` from the parser

`x = ALL (subquery)` with a non-empty right-hand side is now rewritten to
`if(isNull(x), x IN v, ifNull(x = v, 0))`, where `v` is the value from the
scalar subquery. This gives the same results as the former
`x IN (SELECT singleValueOrNull(*) FROM subquery)`:
- a NULL `x` follows `transform_null_in` again;
- the result is `UInt8` for a non-nullable `x`, so for example a table with
  `ORDER BY flag` created from `number = ALL (SELECT 1) AS flag` works again;
- the comparison of a non-NULL `x` with a constant keeps its conversions and
  stays visible to the primary key analysis.

The alias of the scalar subquery was derived from `IAST::getTreeHash`. That
call kept every implementation of `updateTreeHashImpl` in the WebAssembly
parser build, and the `no-formatting-no-dcl` build went 177009 bytes over
its size ceiling. The alias is now a hash of the aggregate function name and
the text of the subquery. Built locally in `clickhouse/wasm-builder`, the
no-formatting/no-DCL `parser.wasm` is 832427 bytes, 42573 under the ceiling.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=106373&sha=latest&name_0=PR&name_1=Build%20(wasm_parser)
PR: ClickHouse#106373

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Parsers/ExpressionListParsers.cpp Resolved
Comment thread src/Parsers/ExpressionListParsers.cpp Resolved
Comment thread src/Parsers/ExpressionListParsers.cpp Resolved
alexey-milovidov and others added 2 commits November 20, 2026 16:46
…result

The previous rewrite of `x = ALL (subquery)` compared `x` with the constant
`tupleElement(_a, 2)` through `if(isNull(x), x IN ..., ifNull(x = ..., 0))`. That had three
problems, reported in the review:

- `x` was copied three times, so quantifiers nested in the left-hand side grew the parsed
  query exponentially (`TOO_BIG_AST` at a depth of 7). It was also a use after move, which
  failed the `clang-tidy` build:
  https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=106373&sha=86b804c12c21de545aeee10e815660f6dfd6d830&name_0=PR&name_1=Build%20%28arm_tidy%2C%204%2F4%29
- A comparison with a constant is not the set comparison of `IN`: `(1, NULL) = ALL (SELECT (1, NULL))`
  became 0, and `NULL = ALL (SELECT (1, 2))` threw `ILLEGAL_TYPE_OF_ARGUMENT`.
- For a `Nullable` key `isNull(x)` is not a constant, so the `if` hid the comparison from the
  primary key analysis.

Now the rewrite is

    x = ALL S --> ifNull(tupleElement(SQ AS _a, 1), 1) OR x IN (SELECT tupleElement(_a, 2))
        where SQ = (SELECT (count(*) = 0, singleValueOrNull(*)) FROM S)

For a non-empty right-hand side this is the former `x IN (SELECT singleValueOrNull(*) FROM S)`
with the value taken from the scalar subquery, so tuples, NULLs, `transform_null_in`, conversions,
the result type and the primary key (also a `Nullable` one) behave as `IN` with a subquery does.
`x` occurs once, and the right-hand side is still evaluated once.

As on master, a correlated subquery is not supported in `= ALL`, because `IN` does not support
it; the correlated case of `05448_all_subquery_missing_row_and_nesting` keeps `<` and `>` only.

PR: ClickHouse#106373

Co-Authored-By: Claude Fable 5.2 <[email protected]>

This branch has not been deployed

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

Labels

can be tested Allows running workflows for external contributors comp-sql-syntax SQL/grammar parsing, AST nodes, syntax-level features. external Author is not a member of the ClickHouse organization pr-bugfix Pull request with bugfix, not backported by default st-discussion When the implementation aspects are not clear or when the PR is on hold due to questions.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

<expr> = ALL (<empty subquery>) should return TRUE (vacuous truth)

7 participants