Skip to content

Add SHUFFLE clause support for SELECT - #100305

Merged
alexey-milovidov merged 59 commits into
ClickHouse:masterfrom
xuir268:shuffle-clause
Nov 7, 2026
Merged

alexey-milovidov merged 59 commits into
ClickHouse:masterfrom
xuir268:shuffle-clause

Conversation

@xuir268

@xuir268 xuir268 commented Mar 21, 2026 •

Copy link
Copy Markdown
Contributor

Adds the SHUFFLE clause, which is used in place of ORDER BY and returns the rows in a uniformly random order: SELECT ... SHUFFLE [LIMIT n]. The shuffle is implemented by first-class processors, as described in #105338 (comment), and works in O(n) instead of O(n * log(n)).

The random choices are made just in time: no random values are generated or stored for the rows in advance.

  • Full shuffle: every row goes to a uniformly random one of max_threads streams; every stream is shuffled in parallel (scattered into cache-sized buckets at random, Fisher-Yates within a bucket); the streams are concatenated. A random scatter followed by uniform shuffles of the parts is a uniformly random permutation, so no keys and no merge are needed.
  • Partial shuffle with LIMIT n: every stream keeps a uniformly random sample of n rows by reservoir sampling (Algorithm L), which skips the rows that cannot get into the sample without looking at them.
  • Merging shuffled streams: the samples are merged by drawing the number of rows to take from every stream as sampling without replacement from the numbers of rows of the streams, and shuffling every output block. In a distributed query, the shards attach sorted random keys (generated at the output, with the distribution of sorted independent uniform keys), and the initiator merges the shuffled streams by them with O(1) memory.

SHUFFLE works without LIMIT, and with LIMIT, OFFSET, LIMIT BY, DISTINCT, GROUP BY, WITH TOTALS, window functions, in distributed queries, and with lazy materialization (SHUFFLE LIMIT n needs no columns before the limit, so the other columns are read only for the sampled rows). Everywhere rows could be limited early (reading from storage, the DISTINCT limit hint, the trivial GROUP BY ... LIMIT, LIMIT pushdown into MongoDB, optimize_distributed_group_by_sharding_key, Merge tables), SHUFFLE is treated like ORDER BY.

ORDER BY rand() and ORDER BY rand64() are executed by the shuffle processors (setting query_plan_use_shuffle_for_order_by_rand, enabled by default) at the end of the plan optimization, after the optimizations working with SortingStep: the values of the rand() column are replaced by sorted random keys, which have the same distribution, so the result is still sorted by this column. It applies when the random value is not used in other expressions, and when there is a LIMIT or the external sorting is disabled (the shuffle does not spill to disk).

The setting inject_random_order_for_select_without_order_by (for tests) injects SHUFFLE instead of ORDER BY rand().

The clause is experimental: allow_experimental_shuffle_query.

Benchmarks (numbers_mt, best of several runs on a loaded 96-core aarch64 machine, external sorting disabled):

Query ORDER BY rand() with sorting shuffle
30M rows, 1 thread 4.79 s 0.50 s
30M rows, 16 threads 1.70 s 0.09 s
10M rows with a String column, 16 threads 0.59 s 0.10 s
100M rows, 16 threads 6.35 s, 1.75 GB 0.43 s, 1.88 GB
100M rows, LIMIT 10 0.10 s 0.08 s
100M rows, LIMIT 1000 0.11 s 0.08 s
100M rows, LIMIT 1000000 0.44 s 0.32 s

The full shuffle still uses about 7% more memory than sorting: the rows a thread receives are copied into its buckets before being shuffled. This could be avoided by scattering into buckets on arrival.

Related: #105338
Related: #87836

Changelog category (leave one):

  • Experimental Feature

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

Added the experimental SHUFFLE clause, used in place of ORDER BY: SELECT ... SHUFFLE [LIMIT n] returns the rows in a uniformly random order (or a uniformly random sample of n rows) in O(n) time, in parallel and in distributed queries. Queries with ORDER BY rand() are executed the same way, up to ten times faster. Enable the clause with allow_experimental_shuffle_query.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.1626-master (included in 26.11 and later)

@CLAassistant

CLAassistant commented Mar 21, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@xuir268

xuir268 commented Mar 21, 2026

Copy link
Copy Markdown
Contributor Author

Hi @alexey-milovidov , if you have time, please take a look. if need anything more, please do let me know

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

clickhouse-gh Bot commented Mar 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [85dece6]

Summary: ✅


AI Review

Summary

Adds the experimental SHUFFLE clause, parallel reservoir sampling, distributed shuffle merging, lazy materialization, and an optimization for ORDER BY rand(). Reviewed head 85dece66e5c5ec9dd179bdc2e7f4f2f9225d207c, including all 37 prior review threads and their replies. No unresolved actionable findings remain.

Output consumers traced: distributed merges retain key order; LIMIT BY preserves the synthetic key; global DISTINCT precedes final reshuffling; projections remove internal columns; lazy reads preserve row identity; totals and extremes retain matching headers; serialized plans preserve appended and replacement keys. Focused runtime checks passed for these paths, including unequal shard populations, nested distributed tables, and mixed local/distributed Merge reads.

Missing context / blind spots
  • ⚠️ Runtime checks used the completed PR build at 9a786eee93bf2c2f0ab04917f067ef826cb6149f, preceding the final merge from master. The final merge's planner changes were inspected; the exact current head was not compiled locally, and the complete CI suite was not rerun during this review.
Final Verdict

Status: ✅ Approve. No new inline findings to post.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Mar 21, 2026
Comment thread src/Parsers/ParserSelectQuery.cpp Resolved
@shankar-iyer shankar-iyer self-assigned this Mar 22, 2026
Switch `SHUFFLE LIMIT` to bounded reservoir sampling, add the experimental `allow_experimental_shuffle_query` setting, update docs/tests, and fix style issues from the CI report.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100305&sha=latest&name_0=PR&name_1=Style+check
Remove the global alias restriction for `SHUFFLE` so disabled mode keeps legacy alias parsing, and update regression tests to use unambiguous clause forms.

PR comment: ClickHouse#100305
Comment thread src/Planner/Planner.cpp Resolved
Apply the  optimization only for positive limits, add  to , normalize , and add a stateless regression test for .

PR comment: ClickHouse#100305
Add  to the first runnable  example so it works under default settings.

PR comment: ClickHouse#100305
xuir268 added 2 commits March 22, 2026 18:51
- Remove trailing whitespace on line 633 of `CommonParsers.h`
- Move `-- { serverError SUPPORT_IS_DISABLED }` inline with the semicolon in `04054_shuffle_disabled_error.sql` so the test runner correctly associates the expected error with the query

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100305&sha=12f6e74bde27f51c8223a68221c984c4581c3ce1&name_0=PR&name_1=Fast%20test
Comment thread src/Interpreters/TreeRewriter.cpp Resolved
When `allow_experimental_shuffle_query = 1` but `allow_experimental_analyzer = 0`,
`TreeRewriter` previously passed the guard and let the query proceed. The old planner
has no `ShuffleStep`, so `SHUFFLE` was silently ignored and non-randomized results
were returned — a correctness bug.

Fix: after the `SUPPORT_IS_DISABLED` gate, always throw `NOT_IMPLEMENTED` in the old
planner path, matching the pattern used for `LIMIT BY ALL`.

Add `04055_shuffle_old_interpreter` to cover the setting-enabled / old-planner case.
xuir268 added a commit to xuir268/ClickHouse that referenced this pull request Nov 2, 2026
Retain sorting for finite UInt64 random-key limits until the replacement can preserve the full integer distribution. Add low-bit regressions.

ClickHouse#100305 (comment)
xuir268 added a commit to xuir268/ClickHouse that referenced this pull request Nov 2, 2026
xuir268 added a commit to xuir268/ClickHouse that referenced this pull request Nov 2, 2026
Cover direct and nested queries under throw and ignore policies.

ClickHouse#100305 (comment)
xuir268 added a commit to xuir268/ClickHouse that referenced this pull request Nov 2, 2026
@alexey-milovidov alexey-milovidov removed the manual approve Manual approve required to run CI label Nov 2, 2026
Correct order-statistic initialization, retain external sorting and limited
`rand64` keys, count input rows before sampling, guard view pushdown and cache
policies, and propagate injected settings. Register and serialize `ShuffleStep`
for remote plans, with numeric formatting for byte flags. Update documentation.

ClickHouse#100305
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=100305&sha=ba3dbe139b1f26d210ce1f1debf4f25b4bb47843&name_0=PR
Cover key distributions and low bits, unequal shards, external sorting, exact
row counts, view pushdown, cache policies, injection and serialization. Remove
unneeded cache resets and avoid integer overflow in distribution assertions.

Static and numerical checks passed. Full compilation and SQL execution remain
unverified locally; CI must validate this revision.

ClickHouse#100305
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=100305&sha=ba3dbe139b1f26d210ce1f1debf4f25b4bb47843&name_0=PR
Comment thread src/Storages/StorageView.cpp Resolved
Comment thread src/Planner/Planner.cpp Resolved
Prevent an outer `LIMIT` from truncating the shuffle population and exclude shuffled views from trivial distributed pushdown. Add population and shard-distribution regression tests.

ClickHouse#100305
ClickHouse#100305 (comment)
ClickHouse#100305 (comment)
Run global `DISTINCT` before final randomization, including inputs from after-aggregation stages. Preserve all shard candidates by disabling distinct limit hints and deferring `LIMIT BY` to the finalizer. Keep existing shard shuffle-key transport intact.

Add duplicate-heavy local and distributed sampling regressions and computed `LIMIT BY` coverage for after-aggregation stages.

ClickHouse#100305
ClickHouse#100305 (comment)
Comment thread src/Planner/Planner.cpp Resolved
alexey-milovidov and others added 2 commits November 3, 2026 20:41
…thout parallel replicas

With parallel replicas the plan also contains `ReadFromRemoteParallelReplicas`
and the merge of the local and the remote shuffled streams, so the reference
did not match in the `ParallelReplicas` stateless tests job.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=100305&sha=latest&name_0=PR&name_1=Stateless%20tests%20(arm_binary%2C%20ParallelReplicas%2C%20s3%20storage%2C%20parallel)
ClickHouse#100305

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov alexey-milovidov added the pr-autogenerated-docs PR that regenerates docs artifacts from source; exempt from the autogenerated-region edit guard label Nov 3, 2026
On a shard, `ShuffleStep` appends `__shuffle_key`, by which the initiator
merges the shuffled streams of the shards. The expression before `LIMIT BY`
is built by the analysis, which does not know about this column, so it was
projected away and a distributed `SHUFFLE LIMIT n BY ...` failed with
`NOT_FOUND_COLUMN_IN_BLOCK`. Add the column to the outputs of that
expression when it is present in the header.

Address review: ClickHouse#100305

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Planner/Planner.cpp Resolved
alexey-milovidov and others added 3 commits November 5, 2026 01:05
…nested `Distributed`

With nested `Distributed` tables, an intermediate server processes the query from
`WithMergeableState` to `WithMergeableState`. Its incoming streams were already
shuffled by the shards below and carry the internal `__shuffle_key` column, so
appending another key threw `The column name __shuffle_key is reserved for SHUFFLE`.
Merge the incoming streams by the key instead, as the initiator does.

Address review: ClickHouse#100305 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The style check now lints `src/Processors/Transforms` for standard containers
(after merging master). Replace `std::vector` and `std::deque` in
`ShuffleTransform` and the new code of `ScatterByPartitionTransform` with
`VectorWithMemoryTracking` and `DequeWithMemoryTracking`.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=100305&sha=e222a2837309af5f038db8c650a6689a5b504e78&name_0=PR&name_1=Style%20check
PR: ClickHouse#100305

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

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The implementation is clean and beautiful. LGTM.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 7, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Nov 7, 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 comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. external Author is not a member of the ClickHouse organization pr-autogenerated-docs PR that regenerates docs artifacts from source; exempt from the autogenerated-region edit guard pr-experimental Experimental Feature 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.

7 participants