Skip to content

Push ORDER BY from outer query into simple VIEWs for distributed optimization - #94102

Merged
alexey-milovidov merged 50 commits into
ClickHouse:masterfrom
matanper:view-over-distributed-table-order-by-pushdown
Jul 3, 2026
Merged

alexey-milovidov merged 50 commits into
ClickHouse:masterfrom
matanper:view-over-distributed-table-order-by-pushdown

Conversation

@matanper

@matanper matanper commented Jan 13, 2026 •

Copy link
Copy Markdown
Contributor

When querying a VIEW over a distributed table with ORDER BY + LIMIT, ClickHouse was performing a full sort on the coordinator instead of using the efficient 'merge sorted streams' optimization.

The root cause is that the Distributed table doesn't see the outer query's ORDER BY clause when reading through a VIEW, so it can't enable the optimization where shards sort their data and the coordinator merges sorted streams.

This fix pushes ORDER BY/LIMIT from the outer query into the VIEW's inner query AST in PlannerJoinTree.cpp:

  1. Detects when the VIEW is a simple SELECT (no UNION, no JOIN, no GROUP BY, no DISTINCT, no existing ORDER BY/LIMIT)
  2. Validates that ORDER BY contains only simple column references from the view
  3. Clones the VIEW's inner query and adds the ORDER BY/LIMIT clauses
  4. Sets the modified query as view_query so the Distributed table sees the ORDER BY

This enables:

  • Each shard to sort its data locally (or use read-in-order optimization)
  • The coordinator to merge pre-sorted streams efficiently
  • Significant performance improvement for ORDER BY + LIMIT queries

The pushdown is intentionally conservative and is skipped whenever it could change results: outer-query filtering (WHERE/PREWHERE/QUALIFY), aggregation/DISTINCT/window functions, LIMIT BY, OFFSET, WITH TIES, WITH FILL, fractional LIMIT, extremes, row policies, additional_table_filters, view/inner-query window or QUALIFY, a column type that differs between the view's declared structure and the inner query, and limit/offset/prefer_column_name_to_alias set either in the view's own SETTINGS clause or in the effective view context (e.g. through a SQL SECURITY DEFINER view's definer settings profile).

Example:

CREATE VIEW v AS SELECT * FROM distributed_table;
SELECT * FROM v ORDER BY col LIMIT 100;

Before: Full sort on coordinator (Sorting (Sorting for ORDER BY))
After: Sort on shards + merge sort on coordinator (Sorting (Merge sorted streams...))

Performance evidence

This optimization removes work on the coordinator: without it the view is an opaque subquery, so every shard streams all of its rows to the coordinator, which then performs the global ORDER BY/LIMIT. With it, each shard applies ORDER BY/LIMIT locally and the coordinator only merges pre-sorted streams (Merge sorted streams), receiving just the per-shard top-n.

Measured on test_cluster_two_shards_localhost (2 shards, 10M rows each = 20M total), SELECT id FROM v ORDER BY ts DESC LIMIT 10, max_threads = 4, median of 7 runs. The A/B was done on the same binary by toggling only the optimization via prefer_column_name_to_alias = 1 — a pure analysis-time flag that disables the pushdown without changing execution; the two outputs are byte-identical (verified by hashing the result), so the comparison isolates this change with no other commits as confounds.

Path Rows the coordinator must ingest + globally sort Wall time, single machine
Without pushdown all 20M (id, ts) rows ≈ 228.9 MiB transferred over the network path ~66 ms
With pushdown per-shard top-10 (≈20 rows total) ~67 ms

On a single machine the wall time is unchanged (equal within run-to-run noise): test_cluster_two_shards_localhost runs its shards in-process (NetworkReceiveBytes = 0), so there is no transfer to save and the per-shard table scan — identical on both paths — dominates. This is exactly why the standard/cloud benchmark suites report no_change: they contain no view-over-networked-Distributed ORDER BY/LIMIT scenario. The transferred-bytes figure (measured by forcing the real network path with prefer_localhost_replica = 0, where the coordinator ingests every shard's rows) quantifies what the optimization eliminates; the benefit scales with row count × shard count and with network latency/bandwidth on real multi-node clusters. The plan-level change (coordinator full sort → Merge sorted streams) is asserted by the stateless test 04241_view_orderby_distributed_optimization.

Changelog category (leave one):

  • Performance Improvement

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

Queries with ORDER BY and LIMIT on VIEWs over distributed tables now use the merge-sorted-streams optimization. The outer ORDER BY/LIMIT is pushed into a simple view's inner query so each shard sorts its data locally and the coordinator merges pre-sorted streams, instead of performing a full sort on the coordinator.

Closes: #92746


Note

Medium Risk
Touches query planning/AST rewriting for VIEW reads; guarded by many semantic checks but regressions are possible in edge cases around filtering/limits/order modifiers.

Overview
Enables an optimization where outer ORDER BY + LIMIT is pushed into a simple VIEW’s inner SELECT (by rewriting SelectQueryInfo::view_query) so underlying Distributed reads can produce merge-sorted streams instead of forcing a full coordinator sort.

The pushdown is intentionally conservative: it only applies to transparent views (single SELECT, no JOIN/GROUP BY/DISTINCT, no existing ORDER BY/LIMIT) and is disabled for outer-query features that can change semantics (filters, OFFSET, LIMIT BY, WITH TIES, WITH FILL, windows, row policies, additional_table_filters), with new stateless tests covering both the positive case and the main rejection cases.

Reviewed by Cursor Bugbot for commit 7f63adb. Bugbot is set up for automated code reviews on this repo. Configure here.

Version info

  • Merged into: 26.7.1.492 (included in 26.7 and later)

…mization

When querying a VIEW over a distributed table with ORDER BY + LIMIT,
ClickHouse was performing a full sort on the coordinator instead of using
the efficient 'merge sorted streams' optimization.

The issue occurs because the VIEW's inner query has no ORDER BY clause.
Without it, shards return unsorted data, forcing the coordinator to do
a full sort rather than merging pre-sorted streams.

This fix injects the outer query's ORDER BY into the VIEW's inner query
AST before it's passed to the interpreter. The fix:

1. Detects when the outer query has ORDER BY and the table expression is a VIEW
2. Clones the VIEW's inner query AST
3. Builds ORDER BY elements from the outer query's sort columns
4. Injects the ORDER BY into the VIEW's inner query
5. Sets this modified query as view_query in SelectQueryInfo

This enables:
- Each shard to sort its data (or use read-in-order optimization)
- The coordinator to merge sorted streams efficiently
- Significant performance improvement for ORDER BY + LIMIT queries

The optimization only applies to simple VIEWs without existing ORDER BY,
GROUP BY, DISTINCT, LIMIT, HAVING, or WINDOW clauses.

Example:
  CREATE VIEW v AS SELECT * FROM distributed_table;
  SELECT * FROM v ORDER BY col LIMIT 100;

Before: Full sort on coordinator (O(N log N))
After:  Sort on shards + merge sort on coordinator (more efficient)
@CLAassistant

CLAassistant commented Jan 13, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jan 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jan 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3b7bc18]

Summary: ✅


AI Review

Summary

This PR pushes outer ORDER BY / LIMIT into simple VIEW inner queries so Distributed can expose the merge-sorted-streams path instead of forcing a full coordinator sort. I did not find a remaining correctness, coverage, or PR-metadata issue on the current head: the risky semantic cases raised earlier in the review are now guarded in pushOrderByIntoView, and the new 04241_view_orderby_distributed_optimization test covers the important rejection paths for this optimization.

Final Verdict

✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jan 13, 2026
For simple views over a single table (no UNION, no JOIN), StorageView
now delegates getQueryProcessingStage() to the underlying storage.
This preserves the underlying storage's capabilities, such as:
- Distributed tables can sort on shards with merge sort at coordinator
- Other storages that support higher processing stages

This fixes the bug where ORDER BY pushdown optimization was not applied
to VIEWs over distributed tables, causing inefficient full sorts instead
of merge sorted streams.

The fix makes VIEW transparent with respect to query processing stage,
which is a cleaner approach than injecting ORDER BY into the view's
inner query.
@matanper
matanper force-pushed the view-over-distributed-table-order-by-pushdown branch from 40343e1 to fdbc3ba Compare January 13, 2026 23:47
The previous commit made StorageView delegate getQueryProcessingStage()
to the underlying storage for ORDER BY optimization. However, this broke
queries with aggregation (e.g., SELECT sum(a) FROM view) because:

- The Distributed table returns stages like WithMergeableState expecting
  partial aggregate function states from shards
- But the VIEW's inner query produces raw columns, not aggregate states
- This caused: "Conversion from UInt64 to AggregateFunction(sum, UInt64)
  is not supported"

Fix: Only delegate to underlying storage when the outer query doesn't
require aggregation. We check:
- query_info.need_aggregate (captures GROUP BY and aggregate functions)
- query_node->isDistinct() (DISTINCT has similar merging requirements)

This preserves the ORDER BY merge-sort optimization while fixing the
aggregation bug.

Test results:
- SELECT * FROM view ORDER BY x LIMIT 10 -> Uses merge sorted streams ✓
- SELECT sum(a) FROM view -> Works correctly (returns 52) ✓
- SELECT DISTINCT a FROM view -> Falls back to FetchColumns ✓
Add NOLINT comment to empty catch block in getQueryProcessingStage.
The empty catch is intentional - it allows fallback to default behavior
when table lookup fails during query processing stage determination.

This follows the established pattern used throughout the codebase for
intentional exception swallowing.
@novikd novikd self-assigned this Jan 19, 2026
novikd
novikd previously requested changes Jan 20, 2026
Comment thread src/Storages/StorageView.cpp Resolved
Comment thread src/Storages/StorageView.cpp Resolved
Comment thread src/Storages/StorageView.cpp Resolved
- Return FetchColumns early when query_tree is not available (analyzer disabled)
- Use query tree for outer query analysis (aggregation, DISTINCT checks)
- Simplify control flow with early returns instead of nested conditionals
- Keep metadata-based approach for finding underlying table in view definition

The optimization delegates getQueryProcessingStage to the underlying storage
for simple views (single SELECT, no UNION, no JOIN), enabling ORDER BY
optimizations like merge sorted streams for distributed tables.
When querying a VIEW over a Distributed table with ORDER BY, the
optimization that merges pre-sorted streams from shards was not applied.
This is because the ORDER BY clause wasn't visible to the underlying
distributed table.

This change pushes ORDER BY (and LIMIT) from the outer query into the
VIEW's inner query AST, enabling the distributed table to see the sort
requirement and apply the merge-sorted-streams optimization instead of
doing a full sort after receiving all data.

Also fix the test to use EXPLAIN instead of EXPLAIN PIPELINE, since
"Merge sorted streams" is a step description that appears in query plan
output, not pipeline output.
When querying a VIEW over a Distributed table with ORDER BY, the
optimization that merges pre-sorted streams from shards was not applied.
This is because the ORDER BY clause wasn't visible to the underlying
distributed table.

This change pushes ORDER BY (and LIMIT) from the outer query into the
VIEW's inner query AST in PlannerJoinTree, enabling the distributed
table to see the sort requirement and apply the merge-sorted-streams
optimization instead of doing a full sort after receiving all data.

Simplified approach: Instead of complex stage delegation in StorageView,
we just push ORDER BY into view_query which is used by StorageView::read().
The underlying Distributed table then naturally sees the ORDER BY.

Also fix the test to use EXPLAIN instead of EXPLAIN PIPELINE, since
"Merge sorted streams" is a step description that appears in query plan
output, not pipeline output.
…b.com:matanper/ClickHouse into view-over-distributed-table-order-by-pushdown
@matanper
matanper force-pushed the view-over-distributed-table-order-by-pushdown branch 5 times, most recently from e926237 to 3a3d6db Compare January 24, 2026 11:58
@matanper
matanper requested a review from novikd January 24, 2026 11:58
@matanper
matanper force-pushed the view-over-distributed-table-order-by-pushdown branch from 3a3d6db to d71d487 Compare January 24, 2026 12:22
@matanper
matanper force-pushed the view-over-distributed-table-order-by-pushdown branch from d71d487 to 513fb91 Compare January 24, 2026 12:36
Comment thread src/Planner/PlannerJoinTree.cpp Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member

Merged the latest master (pushed c59fa22d793..17f3834a507) and re-triggered CI.

  • The merge was clean — no conflicts (unlike the earlier master merges that collided in src/Planner/PlannerJoinTree.cpp). The net PR diff is unchanged: still only src/Planner/PlannerJoinTree.cpp plus the 04241_view_orderby_distributed_optimization test/reference.
  • No API drift from the ~3 days of new master: the merged PlannerJoinTree.cpp passes -fsyntax-only against current master headers.
  • The two non-green checks on the prior head c59fa22d793 were both pre-existing, tracked flakes, unrelated to this planner-only change (as documented above):
    1. Stress test (arm_debug) → Not-ready Set ... 'notNullIn' (STID 0250-4e52, #102803).
    2. Stress test (amd_asan_ubsan) → Hung check (#107941).
      The fresh-master re-run should clear them.

No unresolved review threads; the AI Review verdict is ✅ Approve. The remaining CHANGES_REQUESTED decision is from older, un-dismissed reviews (novikd, and the empty . review) whose threads are all resolved — clearing those is a maintainer action.

Comment thread src/Planner/PlannerJoinTree.cpp Resolved
Address review: `pushOrderByIntoView` rebuilt the pushed-down inner query from
the view's stored definition (`metadata->getSelectQuery().inner_query`), which
does not carry the `SAMPLE`/`FINAL` modifiers applied to the view in the outer
query. Pushing the outer `ORDER BY`/`LIMIT` into that inner query would order
and truncate the full, unsampled, non-final row set below the point where the
modifier applies, so a query such as
`SELECT id FROM v SAMPLE 0.1 ORDER BY ts DESC LIMIT 10` could return the top-N
of the whole view instead of the top-N of the sampled subset.

Skip the optimization whenever the view table expression carries a `SAMPLE` or
`FINAL` modifier, mirroring the existing modifier guard used for the
trivial-count optimization in the same file. Added `FINAL`/`SAMPLE` rejection
cases to `04241_view_orderby_distributed_optimization`.

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

Copy link
Copy Markdown
Member

Addressed the AI review blocker and pushed 17f3834a507..3b7bc18b0b6.

Fix — skip the pushdown when the view carries SAMPLE/FINAL modifiers. pushOrderByIntoView rebuilt the pushed-down inner query from the view's stored definition (metadata->getSelectQuery().inner_query), which does not carry the SAMPLE/FINAL modifiers applied to the view in the outer query. Pushing the outer ORDER BY/LIMIT into that inner query would order/truncate the full, unsampled, non-final row set below the point where the modifier applies, so e.g. SELECT id FROM v SAMPLE 0.1 ORDER BY ts DESC LIMIT 10 could return the top-N of the whole view instead of the sampled subset. Added a guard that skips the optimization whenever the view table expression carries a SAMPLE/FINAL modifier — mirroring the existing modifier guard used for the trivial-count optimization in the same file — plus FINAL/SAMPLE rejection cases in 04241_view_orderby_distributed_optimization. -fsyntax-only on the change passes against current master headers.

CI on the previous head 17f3834a507 (the master re-merge): all three reds were pre-existing, tracked flakes, unrelated to this planner-only change:

@alexey-milovidov alexey-milovidov added can be tested Allows running workflows for external contributors and removed can be tested Allows running workflows for external contributors labels Jul 3, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 3, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

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

Changed lines: Changed C/C++ lines covered: 111/118 (94.07%) · Uncovered code

Full report · Diff report

@alexey-milovidov
alexey-milovidov self-requested a review July 3, 2026 14:36
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 3, 2026
Merged via the queue into ClickHouse:master with commit f62a9d3 Jul 3, 2026
174 checks passed
@groeneai

groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator

Confirmed. Both are pre-existing chronic trunk flakes, unrelated to the planner-only diff.

Both tracked on our side.

@clickgapai

Copy link
Copy Markdown
Contributor

Hi @matanper @alexey-milovidov — while reviewing this PR I found the following:

Could you review the test PR and add the can be tested label if it looks good?
Happy to discuss — close anything that's wrong or already addressed.

@PedroTadim

Copy link
Copy Markdown
Member

Hello! Two questions. 1. Why there is no such setting to enable/disable this optimization? 2. Is this optimization be applied when a LIMIT BY query is issued instead of LIMIT?

pull Bot pushed a commit to admariner/ClickHouse that referenced this pull request Jul 10, 2026
@hshen3197

Copy link
Copy Markdown

V26.7.2 can still see the issue. Is the fix included in this version?

@PedroTadim

Copy link
Copy Markdown
Member

V26.7.2 can still see the issue. Is the fix included in this version?

Can you test on master as well? If it still reproduces please create an issue with a reproducible and I can take a look

zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…ed-table-order-by-pushdown

While resolving conflicts in `src/Planner/PlannerJoinTree.cpp` the
following fixes were applied:

* Removed a duplicate `#include <Parsers/ASTSelectQuery.h>` that broke
  the `arm_tidy` build (`readability-duplicate-include`).
* Restricted `pushOrderByIntoView` so it skips the pushdown when the
  outer query has `GROUP BY`, `HAVING`, `DISTINCT` or window functions.
  Pushing `ORDER BY` into the view's inner query in those cases breaks
  downstream optimizations such as aggregate projection matching,
  which caused `03670_aggregate_projection_in_view` to fail.
* Restricted `pushOrderByIntoView` so it skips the pushdown when the
  outer query has `LIMIT ... OFFSET ...`. Pushing only the outer
  `LIMIT_LENGTH` truncates rows on each shard before the outer offset
  is applied and can produce wrong results.

Also renumbered the new test from `03788_view_orderby_distributed_optimization`
to `04241_view_orderby_distributed_optimization` because master now uses
the `03788_*` prefix for several unrelated tests, and extended the test
to cover the `GROUP BY` and `OFFSET` safety paths.

Addresses review feedback from @novikd, @alexey-milovidov and the
`clickhouse-gh` automated review on
ClickHouse#94102.
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
- Skip pushdown when outer query has `LIMIT ... WITH TIES`: ties are
  resolved globally after ORDER BY, so per-shard `LIMIT_LENGTH` would
  truncate rows that belong to the tie set.
- Skip pushdown when any ORDER BY element uses `WITH FILL`: `WITH FILL`
  synthesizes rows from the sort range, and per-shard fills produce a
  wrong final set after merging.
- Preserve full ORDER BY semantics when rebuilding the AST: copy
  explicit `NULLS FIRST/LAST` and `COLLATE` from `SortNode` (the
  previous code hardcoded `nulls_direction` to match `direction` and
  dropped collation).
- Update test `04241_view_orderby_distributed_optimization`:
  - drop the assertion "View query avoids full sort on coordinator"
    (the outer `Sorting (Sorting for ORDER BY)` step is the outer
    query's own sort; the optimization only changes what the inner
    Distributed step does — merge-sorted-streams vs. full sort)
  - add `EXPLAIN`-based coverage for `NULLS FIRST`, `WITH TIES` (must
    disable pushdown), and `WITH FILL` (must disable pushdown).

CI report: ClickHouse#94102

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
`exact_rows_before_limit` promises an exact `rows_before_limit_at_least`
counter computed over the full pre-`LIMIT` stream. The pushed inner `LIMIT`
becomes a child `LimitTransform` under the outer `LimitTransform`, and
`initRowsBeforeLimit` ignores child limits once it finds the outer limit, so
with the pushdown the counter would be attached above the already-truncated
view output and report only the per-shard top-N. Guard `pushOrderByIntoView`
the same way it already guards `extremes`.

Addresses review feedback on ClickHouse#94102

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Asserts that a view-over-`Distributed` `ORDER BY ... LIMIT` query reports the
full pre-`LIMIT` row count in `rows_before_limit_at_least` when
`exact_rows_before_limit = 1`, and that the pushdown is disabled (no
`Merge sorted streams`) in that case.

Addresses review feedback on ClickHouse#94102

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The setup dropped the `definer_*_04241` users before dropping any leftover
`test_view_definer_*_04241` views from a previous interrupted run. Since the
views depend on the users, `DROP USER IF EXISTS` would throw
`HAVE_DEPENDENT_OBJECTS` while a leftover view still exists. Drop the dependent
views before the users (both in the initial cleanup block and right before the
`DROP USER` statements).

Addresses review feedback on ClickHouse#94102

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…ed-table-order-by-pushdown

Push ORDER BY from outer query into simple VIEWs for distributed optimization
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
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-performance Pull request with some performance 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.

Query loses “merge sorted streams” optimization when querying through a VIEW over Distributed table

9 participants