Skip to content

Add support to use column key as condition in WHERE FIELD - #89603

Merged
alexey-milovidov merged 39 commits into
ClickHouse:masterfrom
adityachopra29:where-field-support
Jul 3, 2026
Merged

alexey-milovidov merged 39 commits into
ClickHouse:masterfrom
adityachopra29:where-field-support

Conversation

@adityachopra29

@adityachopra29 adityachopra29 commented Nov 5, 2025 •

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Queries like SELECT * FROM t WHERE id will now use index skipping on the id column. Resolves #89222

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Details

This change adds support to use column key as condition in WHERE FIELD clauses, enabling index skipping optimization for queries.

Example:

CREATE TABLE test_bool_index (id Int32, value String) 
ENGINE = MergeTree 
ORDER BY id
SETTINGS index_granularity = 8192;

INSERT INTO test_bool_index SELECT number, toString(number) FROM numbers(1000);

EXPLAIN indexes = 1, description = 0 SELECT * FROM test_bool_index WHERE id;

Will give:

Expression
  Expression
    ReadFromMergeTree
    Indexes:
      PrimaryKey
        Keys:
          id
        Condition: (id not in [0, 0])
        Parts: 1/1
        Granules: 1/1
        Search Algorithm: generic exclusion search
      Ranges: 1

This is the same as for the command:

EXPLAIN indexes = 1, description = 0 SELECT * FROM test_bool_index WHERE id != 0;

Resolves #89222

@CLAassistant

CLAassistant commented Nov 5, 2025 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@adityachopra29 adityachopra29 changed the title Add support to use column key as condition in WHERE FIE Add support to use column key as condition in WHERE FIELD Nov 5, 2025
@yariks5s yariks5s added the can be tested Allows running workflows for external contributors label Nov 6, 2025
@clickhouse-gh

clickhouse-gh Bot commented Nov 6, 2025 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a497998]

Summary: ✅


AI Review

Summary

This PR moves bare numeric-key recognition into KeyCondition::extractAtomFromTree so WHERE id, WHERE NOT id, PREWHERE id, minmax skip indexes, and the aggregate-projection no-filter regression all behave correctly. The remaining problem is that projection analysis still rejects non-UInt8 bare filters before the new KeyCondition rule ever runs, so the promised WHERE <numeric key> support is still missing on projection-enabled tables.

Findings

⚠️ Majors

  • [src/Processors/QueryPlan/Optimizations/projectionsCommon.cpp:153] [dismissed by author -- https://github.com/Add support to use column key as condition in WHERE FIELD #89603#discussion_r3369204798] QueryDAG::findInOutputs still throws ILLEGAL_TYPE_OF_COLUMN_FOR_FILTER for bare Int32 / Float64 filters during projection analysis, while this PR's new support only appears later in KeyCondition. That means queries such as SELECT count() FROM t WHERE id still fail on tables with eligible projections under default optimize_use_projections = 1, so WHERE <numeric key> is not actually supported across all projection-capable MergeTree plans. Suggested fix: normalize numeric boolean-context filters before projection analysis as well, or teach projectionsCommon to admit the same boolean-context numeric filter types that the main WHERE path already accepts.
Final Verdict

Not ready: the core non-projection pruning path looks correct now, but projection-enabled queries can still reject WHERE <numeric key> before the new optimization is reached.

@yariks5s yariks5s self-assigned this Nov 6, 2025
@adityachopra29

Copy link
Copy Markdown
Contributor Author

Hi @yariks5s . Any update on this pr? Please tell if anything else if required for me to add to this pr.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Nov 11, 2025
@adityachopra29

Copy link
Copy Markdown
Contributor Author

Hi @alexey-milovidov @yariks5s, Is there any update on this PR's review? Please tell me if there is anything missing from my side on this PR. I am keen to contribute further in ClickHouse.

@yariks5s

yariks5s commented Dec 19, 2025 •

Copy link
Copy Markdown
Member

Hi @alexey-milovidov @yariks5s, Is there any update on this PR's review? Please tell me if there is anything missing from my side on this PR. I am keen to contribute further in ClickHouse.

Hello @adityachopra29, there are failing tests in the Fast test suite. There is probably something wrong with your changes, and this requires further investigation.

@yariks5s yariks5s added the close in a month if not active This will be closed in case of no information label Feb 24, 2026
@adityachopra29

Copy link
Copy Markdown
Contributor Author

Hi, okay I will make the required changes shortly

@clickhouse-gh

clickhouse-gh Bot commented Jun 1, 2026

Copy link
Copy Markdown
Contributor

Dear @yariks5s, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

adityachopra29 and others added 4 commits June 3, 2026 12:55
When rewriting a bare-column filter such as `WHERE id` into
`notEquals(id, 0)`, the zero constant was built with
`output->result_type->getDefault`. For a `Nullable` (or `LowCardinality`)
key column this yields `NULL`, turning the rewrite into
`notEquals(key, NULL)`, which evaluates to `NULL` under three-valued logic
and disables index analysis. Take the zero value from the nested
non-nullable type instead, while still creating the const column with the
original `result_type`.

Co-authored-by: Cursor <[email protected]>
The `!isUInt8` guard excluded `Bool`/`UInt8` key columns from the
bare-column rewrite, so `WHERE flag` stayed a bare input node.
`KeyCondition::extractAtomFromTree` only builds index atoms from function
nodes such as `notEquals(flag, 0)`, so the boolean-key case from ClickHouse#89222
produced no index ranges. Remove the guard so a genuine `Bool`/`UInt8`
key column is also rewritten to `notEquals(flag, 0)`, and add a regression
test covering `ORDER BY flag` with `WHERE flag`.

Co-authored-by: Cursor <[email protected]>
The `EXPLAIN` reference for the `Float64` key case expected
`(x not in [0, 0])`, but a `Float64` zero renders as `0.`, so update it to
`(x not in [0., 0.])`. Also revert an unrelated stray blank line in
`KeyCondition::extractAtomFromTree`.

Co-authored-by: Cursor <[email protected]>
The previous approach rewrote a bare-column filter (`WHERE id`) into
`notEquals(id, 0)` in `analyzeFilter`, which fired for every filter in
every query. That had broad side effects: it crashed on `Nothing` typed
columns (`materialize(NULL)`), and it broke optimizer passes that match on
bare-column filters produced by `EXISTS`/`IN`-to-join rewrites
(`query_plan_convert_any_join_to_semi_or_anti_join`, `rewrite_in_to_join`).

Revert the planner rewrite and instead recognize a bare numeric key column
directly in `KeyCondition::extractAtomFromTree`, treating it as
`key not in [0, 0]`. This is scoped to index analysis on real key columns,
so it does not disturb the logical plan or the optimizer, handles
`Nullable`/`LowCardinality` keys via the nested type, and covers
`WHERE NOT key` for free (the surrounding `not` inverts the atom into
`key == 0`). See ClickHouse#89222.

Co-authored-by: Cursor <[email protected]>
@adityachopra29

Copy link
Copy Markdown
Contributor Author

Hi @alexey-milovidov, is anything else remaining in this PR? If not, then we can proceed to get it merged...

@alexey-milovidov

Copy link
Copy Markdown
Member

Merged the latest master (789e3a6b6cb) to refresh CI — the branch was ~900 commits / 3 days behind and the only red checks were known infrastructure flakes (see below). The merge is clean and the net PR diff is byte-identical (6 files, +250/-1).

I verified the merge is semantically sound, since master has been actively changing the same KeyCondition::extractAtomFromTree area (the ifNull(X, 0) / coalesce(X, 0) boolean rewrite and the LIKE/empty-pattern PK-range work):

  • The new bare-numeric-key block sits in the non-function, non-constant branch of extractAtomFromTree, which is orthogonal to all of master's recent changes there (those are in the function-node branch).
  • isKeyPossiblyWrappedByMonotonicFunctions still has the exact 6-argument signature the block calls, and candidates.has_filter (used by the optimizeUseAggregateProjections guard) is unchanged.

The three CI failures on the previous head were all pre-existing, unrelated flakes already tracked by open issues, not caused by this index-pruning change (it only affects part/granule selection, never query results):

Waiting on the fresh CI run to go green.

Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
The bare-numeric-key rule added for ClickHouse#89222 treats `WHERE id` as `id != 0`
(a `FUNCTION_NOT_IN_RANGE` over `[0, 0]`). For a `Nullable` (or
`LowCardinality(Nullable)`) key, primary-key analysis maps a NULL key
value to `+Inf` for `NULLS LAST` ordering, so a granule that holds only
NULL looks definitely outside `[0, 0]` and the atom reports it as an
exact, definite match. But `WHERE nullable_key` evaluates to NULL for
those rows and filters them out.

Ordinary pruning only over-reads, so it stays correct, but the
exact-count / implicit-projection optimization
(`SELECT count() ... WHERE nullable_key` with
`optimize_use_implicit_projections = 1`) would count such NULL-only
granules without reading them and return a wrong result.

Skip the optimization for `Nullable` keys: the atom is left unset
(`FUNCTION_UNKNOWN`), reverting to reading and filtering those rows.

Add `04490_where_field_nullable_key_exact_count`, which asserts the
optimized `count()` equals a full-scan ground truth for `Nullable(Int32)`
and `Nullable(Float64)` keys with a NULL-only part.

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

Copy link
Copy Markdown
Member

Addressed the AI-review blocker about Nullable keys (KeyCondition.cpp:3924) in 8d57887b895.

The hole. The bare-key rule treats WHERE id as id != 0 (a FUNCTION_NOT_IN_RANGE over [0, 0]). For a Nullable (or LowCardinality(Nullable)) key, primary-key analysis maps a NULL key value to +Inf (NULLS LAST), so a granule that holds only NULL looks definitely outside [0, 0] and the atom reports it as an exact, definite match. But WHERE nullable_key is NULL for those rows and filters them out. Ordinary pruning only ever over-reads, so it stays correct, but the exact-count / implicit-projection optimization (SELECT count() … WHERE nullable_key with optimize_use_implicit_projections = 1) counts those NULL-only granules without reading them and returns a wrong count.

The fix. Skip the bare-key optimization for Nullable keys (guard on removeLowCardinality(key_column_type)->isNullable()). The atom is left unset (FUNCTION_UNKNOWN), so those rows are read and filtered, which is correct. I went with "disable for nullable" (the bot's first suggested option) rather than marking the atom relaxed, because for a FUNCTION_NOT_IN_RANGE atom relaxed forces can_be_false = true, which after the built-in negation forces can_be_true = true — i.e. it disables pruning entirely anyway, so it is equivalent in effect but less clear.

Regression test. 04490_where_field_nullable_key_exact_count builds a Nullable(Int32) / Nullable(Float64) primary key with a NULL-only part plus a part containing 0, and asserts the optimized count() (with optimize_use_projections = 1, optimize_use_implicit_projections = 1) equals a full-scan countIf ground truth (which cannot prune). Before the fix the NULL-only part was over-counted; after it they match.

Verification. I confirmed the mechanism on a recent master ASan binary (26.6.1.1): SELECT count() FROM t WHERE id != 0 on the same nullable table returns 109 instead of the correct 9 under implicit projections — the new bare-key atom is byte-identical to that != 0 atom, so WHERE id inherited it. The edited KeyCondition.cpp passes -fsyntax-only against the real headers; I could not run the new stateless test end-to-end locally (a full build did not fit this session), so it relies on fresh CI.

Heads-up (pre-existing, out of scope here): the explicit form SELECT count() FROM t WHERE nullable_key != 0 exhibits the same exact-count over-count on master, independent of this PR — the notEquals atom builds the identical FUNCTION_NOT_IN_RANGE with no nullable guard, and the exact-range consumption has none either. That looks like a separate, latent bug in the exact-count path for Nullable keys with NULL-only granules; it probably deserves its own issue/PR rather than being folded in here. @alexey-milovidov, let me know if you'd prefer I open one.

alexey-milovidov and others added 2 commits June 30, 2026 09:31
The test exercised the `Nullable`-key exact-count guard with a bare
`WHERE id` over a `Nullable(Int32)` / `Nullable(Float64)` key. But a bare
`Int32` / `Float64` column in a boolean context is rejected by the
projection filter check with `ILLEGAL_TYPE_OF_COLUMN_FOR_FILTER` (an
orthogonal, pre-existing limitation), so the query threw before it could
ever reach the exact-count path the test means to cover.

Switch the key to `Nullable(UInt8)` / `Nullable(Bool)`, which are valid
filter types, so `WHERE flag` reaches the implicit-projection / exact-count
optimization. With the `KeyCondition` guard the bare-key atom is left
`FUNCTION_UNKNOWN` for `Nullable` keys, so the NULL-only granule is read and
filtered and the count matches the full-scan ground truth. Without the guard
the same NULL-only granule is reported as a definite match for `flag != 0`
and over-counted, so the test is a genuine regression test for the fix.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The latest `KeyCondition` change deliberately leaves a bare `Nullable` key
as `FUNCTION_UNKNOWN` (it would otherwise over-count NULL-only granules in
the exact-count path, see ClickHouse#89222). With `force_primary_key = 1` on the
`Nullable` case, `ReadFromMergeTree::selectRangesToRead` then sees
`key_condition.alwaysUnknownOrTrue()` and throws `INDEX_NOT_USED` instead of
producing the expected rows.

Drop `force_primary_key` from the `Nullable` case: the query correctly falls
back to a full scan and filter and returns the same rows. The
exact-count correctness for `Nullable` keys is covered by
`04490_where_field_nullable_key_exact_count`.

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

Copy link
Copy Markdown
Member

Fixed both Fast test failures on 8d57887b895 (591f64ef4e8, 9a50b1cd173). Both are test-only; the KeyCondition Nullable guard and the optimizeUseAggregateProjections filter guard are unchanged and correct.

03703_primary_key_condition_boolean_column (Test 3, the Nullable case). As the AI review and the inline bot comment noted, the new KeyCondition change deliberately leaves a bare Nullable key as FUNCTION_UNKNOWN, so WHERE id with force_primary_key = 1 now throws INDEX_NOT_USED. Dropped force_primary_key from that case — the query correctly falls back to a full scan and returns the same rows (1 one / 2 two). The other cases are unchanged.

04490_where_field_nullable_key_exact_count. This one was the deeper problem. The test built the Nullable key from Nullable(Int32) / Nullable(Float64), but a bare Int32 / Float64 column in a boolean context is rejected by the projection filter check with ILLEGAL_TYPE_OF_COLUMN_FOR_FILTER (the orthogonal, pre-existing projectionsCommon limitation called out earlier in this PR). So SELECT count() ... WHERE id threw before it could ever reach the exact-count path the test means to cover — it can never pass as written.

Switched the key to Nullable(UInt8) / Nullable(Bool), which are valid filter types, so WHERE flag actually reaches the implicit-projection / exact-count optimization. This makes it a genuine regression test for the Nullable guard:

  • I confirmed on a recent binary that SELECT count() FROM t WHERE flag != 0 SETTINGS optimize_use_implicit_projections = 1 over the same NULL-only-granule table returns 105 instead of the correct 5 — the NULL-only granule is reported as a definite match for != 0. The new bare-key atom is byte-identical to that != 0 atom, so without the guard WHERE flag would over-count the same way.
  • With the guard the atom is left FUNCTION_UNKNOWN, the granule is read and filtered, and the count matches the full-scan countIf ground truth (5 = 5 → 1), which is what the updated reference asserts.
  • Verified the updated 04490 passes end-to-end (all assertions yield 1, no ILLEGAL_TYPE_OF_COLUMN_FOR_FILTER).

Note: the equivalent over-count on the explicit WHERE nullable_key != 0 form is pre-existing on master, independent of this PR, and is left out of scope here as discussed.

Resolves the conflict in `optimizeUseAggregateProjection.cpp`. While this PR
was pending, `master` independently added the same "don't install the
projection-rewrite DAG as the pruning filter when there is no real filter"
guard, but as the more precise per-candidate `candidate.has_filter`
(introduced in `9b6760887fc`, "Support WHERE clause for aggregate
projections") rather than the whole-query `candidates.has_filter` this PR
used.

`candidate.has_filter` is a strict refinement: it is true only when this
candidate's residual filter survives after stripping the projection's own
implied `WHERE`, so it installs `nullptr` in a superset of the cases this PR
guarded — both when the query has no filter (this PR's case, test
`04356`) and when the projection's `WHERE` fully covers the query filter
(residual empty), where the DAG's first output is likewise a bare projection
key column. Adopted `master`'s version and kept a comment documenting the
ClickHouse#89222 bare-key interaction (a bare numeric key column is read as
`key != 0`, so it must not be mistaken for a filter predicate).

The net PR diff is now the `KeyCondition` bare-key rule (with the
`Nullable` guard), this documentation comment, and the three tests.

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

Copy link
Copy Markdown
Member

Merged the latest master (f54adf1f5bc) to resolve a conflict that appeared in optimizeUseAggregateProjection.cpp (the branch was ~1193 commits behind).

The conflict is a convergence: while this PR was pending, master independently added the same "don't install the projection-rewrite DAG as the pruning filter when there is no real filter" guard — in commit 9b6760887fc ("Support WHERE clause for aggregate projections") — but as the more precise per-candidate candidate.has_filter rather than the whole-query candidates.has_filter this PR introduced.

candidate.has_filter is a strict refinement of candidates.has_filter: it is true only when the candidate's residual filter survives after stripping the projection's own implied WHERE, so it installs nullptr in a superset of the cases this PR guarded — both when the query has no filter (this PR's case, test 04356) and when the projection's WHERE fully covers the query filter (residual empty), where the DAG's first output is likewise a bare projection key column. I traced all three 04356 cases and the behaviour is identical either way, so I adopted master's guard and kept a comment documenting the #89222 bare-key interaction (a bare numeric key column is read as key != 0, so it must not be mistaken for a filter predicate).

As a result the net diff to optimizeUseAggregateProjection.cpp is now just that documentation comment; the functional guard line is byte-identical to master. The KeyCondition bare-key rule (with the Nullable guard) and the three tests are unchanged. The merge is clean and MERGEABLE again; CI is re-running on a49799889ce.

@clickhouse-gh

clickhouse-gh Bot commented Jul 2, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.50% 85.50% +0.00%
Functions 92.60% 92.60% +0.00%
Branches 77.70% 77.70% +0.00%

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

Full report · Diff report

@alexey-milovidov

Copy link
Copy Markdown
Member

CI triage after the latest master merge (a4979988):

Public CI — the only red is Stateless tests (amd_tsan, s3 storage, parallel, 2/2), and it did not fail any test: it errored with Error waiting for container: Canceled: grpc: the client connection is closing: context canceled (runner/container cancellation). Re-triggered the job. The PR's own tests (03703, 04356, 04490) pass, and Mergeable Check was red only because of this one job.

CH Inc sync — red from three failures, all unrelated to this change (which only touches the read/index path in KeyCondition and aggregate-projection selection):

  • Integration tests (amd_asan_ubsan, db disk, old analyzer, 1/7): test_distributed_cache_read_failover_to_another_server — distributed-cache failover.
  • Stress test (arm_asan_ubsan, meta in keeper): Logical error: Data part ... does not have removal tid (transactions) followed by Cannot start clickhouse-server. Neither 03703 nor 04356 failed in this run.
  • Config Workflow: The following new workflow files do not have the 'private_' prefix — a sync-tooling check; this PR adds no workflow files (from a superseded run).

Re-triggered the failed sync jobs.

On the AI review's remaining "Not ready" note — SELECT count() ... WHERE <non-UInt8 numeric key> throwing ILLEGAL_TYPE_OF_COLUMN_FOR_FILTER under optimize_use_projections = 1: this is the pre-existing projectionsCommon filter-type check, which this PR does not touch and which is documented as an orthogonal limitation in the 04490 comment. The earlier pre-projection rewrite was intentionally reverted in favor of the KeyCondition approach, so this is out of scope here.

The earlier approval was auto-dismissed by the later commits and the master merge.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 3, 2026
Merged via the queue into ClickHouse:master with commit 2b01bde Jul 3, 2026
518 of 520 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 3, 2026
pull Bot pushed a commit to AnotherGenZ/ClickHouse that referenced this pull request Jul 21, 2026
…allel-replicas read paths

A bare non-UInt8 column in WHERE (implicit `col != 0`) is coerced by the
normal read path but was rejected with ILLEGAL_TYPE_OF_COLUMN_FOR_FILTER on
the projection and parallel-replicas read paths (issue ClickHouse#110795). The defect no
longer reproduces on master (fixed via the WHERE-field-condition work in
ClickHouse#89603 and the projection filter fix in ClickHouse#106590), but there was no test
covering the non-UInt8 case across both alternative read paths. This adds one.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…upport

Add support to use column key as condition in `WHERE` FIELD
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…allel-replicas read paths

A bare non-UInt8 column in WHERE (implicit `col != 0`) is coerced by the
normal read path but was rejected with ILLEGAL_TYPE_OF_COLUMN_FOR_FILTER on
the projection and parallel-replicas read paths (issue ClickHouse#110795). The defect no
longer reproduces on master (fixed via the WHERE-field-condition work in
ClickHouse#89603 and the projection filter fix in ClickHouse#106590), but there was no test
covering the non-UInt8 case across both alternative read paths. This adds one.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
valerypetrov pushed a commit to valerypetrov/ClickHouse that referenced this pull request Nov 11, 2026
`optimizePrimaryKeyConditionAndLimit` already passes `limit + offset` of
the first `LIMIT` above a read to the read. When that is 0 and the `LIMIT`
does not read till end (`exact_rows_before_limit`, totals), the query
takes no row from the read, yet `ReadFromMergeTree::selectRangesToRead`
ran the whole primary key and skip index analysis for it. On the table of
ClickHouse#125812 (244141 marks, `WHERE c2` on a `UInt8` key column, which ClickHouse#89603
turned into a key condition) that is a 41053-step exclusion search per
`SELECT ... LIMIT 0`, the query BI tools and drivers issue to discover
column types.

The pass now marks such a read, and the analysis returns right after
partition pruning, statistics pruning and sampling, with no ranges. The
read then builds the empty pipe it builds for any read that selects
nothing. Kept: `force_primary_key`, `force_index_by_date`,
`force_data_skipping_indices`, SAMPLE validation, `rows_before_limit` with
`exact_rows_before_limit`. The return precedes the query condition cache,
which records the granules missing from a selection as not matching.
Not skipped where the ranges are still needed: parallel replicas,
`make_distributed_plan`, and forced or preferred projections.

Behaviour change: `max_rows_to_read` and `max_partitions_to_read` no
longer reject a `LIMIT 0` query, which reads nothing.

Closes ClickHouse#125812

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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 pr-improvement Pull request with some product improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

WHERE field does not use PK or data skipping indices

5 participants