Repository navigation
Conversation
When using a CTE with SELECT *, the entire compound column (Tuple, JSON, etc.)
was being read even when only a subcolumn was needed. This is because:
1. CTE projects the full column (e.g., 'event')
2. Outer query resolves 'event.class_name' as getSubcolumn(event, 'class_name')
3. Column pruning sees 'event' as used, reads entire column
This new pass (SubcolumnPushdownPass) runs before RemoveUnusedProjectionColumnsPass
and transforms getSubcolumn calls into direct column references by pushing the
subcolumn access into the source subquery's projection.
Example transformation:
Before: WITH foo AS (SELECT event FROM t) SELECT event.class_name FROM foo
-> getSubcolumn(event, 'class_name'), reads entire 'event' Tuple
After: WITH foo AS (SELECT event.class_name FROM t) SELECT event.class_name FROM foo
-> direct column access, reads only 'event.class_name'
This enables proper subcolumn pruning for CTEs and subqueries, significantly
reducing I/O for queries that access only specific subcolumns of compound types.
Added a new analyzer pass that enables subcolumn pruning for CTEs and subqueries with SELECT *. Queries accessing subcolumns of compound types (Tuple, JSON, Map, Array, Nullable, Nested) through CTEs now read only the needed subcolumn instead of the entire compound column. Example: WITH foo AS (SELECT * FROM t) SELECT event.class_name FROM foo now reads only 'event.class_name' instead of the full 'event' column.
Contributor
|
Workflow [PR], commit [b54b7f9] Summary: ❌
|
…tionColumnsPass Running SubcolumnPushdownPass before RemoveUnusedProjectionColumnsPass was breaking column pruning for views queried via remote(). The RemoveUnusedProjectionColumnsPass needs to run first to ensure only required columns are read from views on shards. This fixes the 03550_analyzer_remote_view_columns test failure.
FunctionToSubcolumnsPass converts functions like isNull() into subcolumn accesses (e.g., column.null). These newly created subcolumn accesses need to be pushed down into views and subqueries for proper optimization. Running SubcolumnPushdownPass again after FunctionToSubcolumnsPass ensures that all subcolumn accesses are properly handled. Fixes test failure in 02932_refreshable_materialized_views_1.
Extend SubcolumnPushdownPass to handle not just getSubcolumn() function calls, but also direct ColumnNode references with subcolumn names (e.g., column.null, tuple.a). This is critical for handling subcolumn accesses created by FunctionToSubcolumnsPass, which converts function calls like isNull(col) into direct subcolumn references (col.null). These references need to be pushed down into views and subqueries for proper optimization. Changes: - Added processSubcolumnNode() to detect and handle direct subcolumn refs - Refactored shared logic into pushdownSubcolumn() helper method - processGetSubcolumnFunction() handles explicit getSubcolumn() calls - Both types now correctly push down through QueryNode sources Fixes the error "Not found column __table2.column.null in block" that occurred when querying views with IS NULL conditions. Tested with: - 02932_refreshable_materialized_views_1 (IS NULL through views) - 03790_cte_subcolumn_pruning (tuple subcolumns through CTEs) - 03550_analyzer_remote_view_columns (column pruning through views)
- Skip optimization for tables that don't support subcolumns (e.g., system tables) - Clone non-CTE QueryNodes before modification to avoid shared state corruption - Check optimization feasibility before making any modifications - Add VIEW tests (optimized user table and non-optimized system table) - Rename test file to reflect broader coverage (CTE, subquery, VIEW) - Add detailed comments explaining each conditional check
…olumn-pushdown-pass
Cloning a child of a JoinNode would invalidate column references in the ON clause, causing LOGICAL_ERROR "does not have valid source node". Skip the subcolumn pushdown optimization for sources inside JOINs since cloning one side would leave the join condition columns pointing to the deallocated original node.
Two issues fixed: 1. Cloning a child of a JoinNode would invalidate column references in the ON clause, causing LOGICAL_ERROR "does not have valid source node". 2. Always clone the source QueryNode before modifying (including CTEs) to avoid modifying shared state that might be used in multiple contexts (e.g., EXPLAIN, caching). Added safety check for projection size to prevent undefined behavior if projection nodes and columns get out of sync.
…hrough JOINs Two issues fixed: 1. Cloning a child of a JoinNode would invalidate column references in the ON clause, causing LOGICAL_ERROR "does not have valid source node". 2. Always clone the source QueryNode before modifying (including CTEs) to avoid modifying shared state that might be used in multiple contexts (e.g., EXPLAIN, caching). Added safety check for projection size to prevent undefined behavior if projection nodes and columns get out of sync.
Refactored SubcolumnPushdownPass to use a two-pass approach: 1. First pass collects all getSubcolumn calls grouped by source 2. Second pass clones each source once and adds all needed subcolumns This fixes the LOGICAL_ERROR that occurred when accessing multiple subcolumns from the same base column (e.g., ProfileEvents.keys and ProfileEvents.values) through CTEs or UNIONs. Also moved RemoveUnusedProjectionColumnsPass to run after SubcolumnPushdownPass so it can clean up unused base columns. Added tests for multi-subcolumn access patterns.
matanper
force-pushed
the
add-subcolumn-pushdown-pass
branch
from
January 15, 2026 21:58
3394414 to
00e5625
Compare
- Remove unused base columns directly in the pass instead of relying on a second RemoveUnusedProjectionColumnsPass - Add explanatory comments above each conditional check
Use std::greater<>() instead of std::greater<size_t>() for transparent functor.
matanper
force-pushed
the
add-subcolumn-pushdown-pass
branch
from
January 16, 2026 21:28
fa1ddf8 to
7b313ae
Compare
When cloning a source for subcolumn pushdown optimization, all columns referencing that source must be updated to point to the cloned source. Previously only subcolumn access columns were updated, leaving other columns (e.g., `id` in `SELECT id, data.a FROM view`) with orphaned source references, causing LOGICAL_ERROR.
…ckHouse into add-subcolumn-pushdown-pass
Member
|
🕵 Merged |
…ion rewrites in `SubcolumnPushdownPass` Both boundary predicates are evaluated after the aggregation, so a `getSubcolumn` there must not be replaced by a standalone subcolumn when the query groups by the parent column (`NOT_FOUND_COLUMN_IN_BLOCK`). Co-Authored-By: Claude Opus 5.5 <[email protected]>
The scalar subquery `(SELECT sum(json.b.:Int64) FROM (SELECT json FROM p_w))` is there to read the whole `json` column, in contrast to the direct typed subcolumn read. With `optimize_push_subcolumns_into_subqueries` the subcolumn is pushed into the subquery, so it reads as `NULL` the same as the direct read. Disable the pushdown for that query to keep its intent. https://s3.amazonaws.com/clickhouse-test-reports/PRs/94105/bbe2a8104bc1f14c9707baead8d71cb76dfad65f/pr/result_stateless_tests_arm_binary_parallel.json Co-Authored-By: Claude Opus 5.5 <[email protected]>
…arts After a lazy `JSON` type hint change (`enable_json_lazy_type_hints`), reading the whole column from an old part converts it to the new type, while reading the subcolumn exposes the old type, so `optimize_push_subcolumns_into_subqueries` changed the result (e.g. `NULL` instead of `15` for `j.b.:Int64` after removing the hint `b UInt64`). Push a subcolumn of a column with dynamic subcolumns only if every part of the `MergeTree` table stores the column under exactly the type of the table metadata, or the storage is `Memory` or a `Log` engine. Restore `05301_json_shared_typed_paths_alter` with the pushdown enabled and add a focused off/on regression test. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…torage-cast)` A lazily loaded table is reached through a storage proxy whose snapshot carries no parts, so the cast is expected to fail for it and the pushdown of `JSON` subcolumns is skipped (fail-close). Fixes the `storage_casts` style check: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=94105&sha=c16459d7d598ce6c48e024e2261f10fcb4b81d56&name_0=PR&name_1=Style%20check PR: ClickHouse#94105 Co-Authored-By: Claude Opus 5.5 <[email protected]>
With `apply_mutations_on_fly = 1` the pending mutations are applied to the whole column, but not to a subcolumn read directly, so `SubcolumnPushdownPass` exposed the old values (`sum(tup.a)` returned `3` instead of `84` after a pending `ALTER TABLE t UPDATE tup = tuple(42, 'z')`). Keep the extraction from the parent for the columns the mutations snapshot reports as changed on the fly, and for storages other than `MergeTree` when mutations are applied on the fly. Address review: ClickHouse#94105 (comment) Co-Authored-By: Claude Opus 5.5 <[email protected]>
…he source query settings `SubcolumnPushdownPass` decided whether a column may be changed on the fly only by the explicit assignment targets of the pending mutations, but `MutationsInterpreter` also recalculates the `MATERIALIZED` columns depending on them (directly or through `ALIAS` and other `MATERIALIZED` columns). Use `MaterializedColumnDependencies::findColumnsToRecalculate`, the same check `AlterConversions` uses for the read, to reject those columns too. The storage check also used the context of the outer query, while the table is read with the settings of the source subquery, so a subquery enabling `apply_mutations_on_fly` locally bypassed the guard for `Merge` and other proxy storages. Use the context of the source query instead. Extend `05459_subcolumn_pushdown_mutations_on_fly` with both cases. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Member
|
🕵 Merged |
Index analysis matches primary key, partition key and skip index expressions against the query, so replacing `getSubcolumn(tup, 'a')` with a direct read of `tup.a` broke pruning by a key defined over `getSubcolumn(tup, 'a')`. Skip columns used by keys and secondary indices, as `FunctionToSubcolumnsPass` does. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Include `ExpressionActions.h` for the secondary index check, and add a test that the primary key and a skip index over `getSubcolumn(tup, 'a')` still prune granules with `optimize_push_subcolumns_into_subqueries` enabled. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… when the parent stays read `SubcolumnPushdownPass` validated a subcolumn only against the metadata of the storage in the subquery. A forwarding storage (`Merge`, `Buffer`, `MaterializedView`, `Alias`, a lazily loaded table, ...) passes the flattened name `tup.a` to the underlying table, where it can resolve to a declared column `tup.a`, skip a conversion of the whole column, or bypass a primary key or skip index that the forwarding storage's metadata does not have. Only storages that read their own data (`MergeTree` family, `Memory`, the `Log` family, `file`, `url` and object storages) are accepted now. The pass also added a subcolumn read even when the whole column was still read by the subquery (another projection column, `WHERE`, ...) or referenced directly by the outer query, which reads more and prunes nothing. Now the subcolumns of a column are pushed down only if every reference to it is a pushed subcolumn access and the subquery reads the column nowhere else. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Projections are matched against the expressions of the query, so a projection defined over `getSubcolumn(t, 'a')` is not selected for a query that reads the column `t.a` directly. `isKeyColumn` now also checks `ProjectionDescription::getRequiredColumns` of every projection, so both aggregate projection selection and normal projection key pruning keep working when `optimize_push_subcolumns_into_subqueries` is enabled. Co-Authored-By: Claude Opus 5.5 <[email protected]>
After merging `master`, `FunctionNode::isAggregateFunction` no longer exists: it was replaced by `isAggregationCall`, which has the same meaning here (an aggregate function that is not a window call). Co-Authored-By: Claude Fable 5.2 <[email protected]>
Member
|
🕵 Merged |
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
When a CTE or a subquery projects a whole compound column (
Tuple,Map,JSON, ...) and the outer query only reads one subcolumn of it, the whole column was read:event;event.class_nameintogetSubcolumn(event, 'class_name');eventas used and reads the entire column.The new query tree pass
SubcolumnPushdownPassruns afterFunctionToSubcolumnsPassand rewrites thosegetSubcolumncalls into direct column references, pushing the subcolumn access into the projection of the source subquery:The rewrite is skipped whenever it would change the rows the source query produces -
DISTINCT,GROUP BY,LIMIT BY, window functions andQUALIFYall key off the projected expressions - and the base column is only dropped from the projection once every one of its references has been rewritten. The new settingoptimize_push_subcolumns_into_subqueries(on by default) turns the pass off.Related: #112688 implements the same optimization as
PushSubcolumnsIntoSubqueriesPass; only one of the two should be merged.Closes: #92455
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Read only the needed subcolumns of a compound column when it is selected through a CTE or a subquery, instead of the whole column.
🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/94105]