Native random sampling in ClickHouse
ClickHouse's SAMPLE clause runs aggregations over a deterministic subset of rows selected by a hash-based sample key, which must be part of the primary key so granules above the hash threshold can be skipped. On a 30M-row UK house price dataset, sipHash64(postcode1, postcode2) spreads rows evenly across buckets, while a low-cardinality column like county skews badly because Greater London holds 13% of sales. Sampling works by fraction or by minimum row count, and the _sample_factor virtual column scales sums and counts back to full-dataset estimates; avg needs no adjustment. A 10% sample cut a grouped analytical query from 687 ms to 141 ms by reading 384 of 3,719 granules, with sales estimates about 7–8% off, which is acceptable for exploratory work.
Related posts
- ClickHouse Newsletter February 2023: A ‘Sample’ of What’s Happening in the Community
ClickHouse mediumAdept
ClickHouse's SAMPLE BY clause trades exact answers for speed on very large tables, illustrated with a 425-billion-row Wikistat dataset. A full-table monthly average took about 278 seconds. Taking the first million rows was fast but biased, while a table with a hashed sampling key (cityHash64(path)) placed first in the ORDER BY answered from a 1% sample in about 6 seconds with reasonable accuracy. Sums must be scaled up by the sampling factor. The newsletter also lists upcoming webinars and meetups, recaps 23.1 features (experimental inverted indices, parameterized views, query result cache) and links recent blog posts.
- How to take random samples from big PostgreSQL tables
Render mediumAdept
Random sampling from billion-row PostgreSQL tables with ORDER BY random() scans every row and runs a top-N heapsort, taking over a minute. A WHERE random() < p filter (Bernoulli sampling) drops the sort and halves runtime, but it still reads every heap page. TABLESAMPLE SYSTEM picks whole 8kB heap blocks and returns about 10k rows in roughly 50ms, at the cost of a nondeterministic result count and correlated rows within each block. A 10k-trial simulation showed result sizes and runtimes are normally distributed with modest row overlap. For joins, sample one side (the "many" side) before joining, and never sample both tables independently.
- ClickHouse and The One Billion Row Challenge
ClickHouse mediumAdept
ClickHouse Local solves the One Billion Row Challenge (min/mean/max temperature per station from a 13GB text file) in about 20 seconds on an 8-core Hetzner VM, versus nearly 3 minutes for the Java baseline. Reading lines with LineAsString and splitting on ';' instead of using the CSV parser cut the time from 27.6s to 19.9s. Loading into a Memory table first, or precomputing aggregates with a Materialized View into an AggregatingMergeTree via a Null engine, makes later queries near-instant but costs 21–26s of load time, so neither beats the single-scan query end to end. ClickHouse SQL using randCanonical and a Box-Muller transform also generates the dataset 6.8x faster than the Java generator.
- Generating Random Data in ClickHouse
ClickHouse mediumAdept
ClickHouse 22.10 added random functions for non-uniform distributions (randNormal, randBinomial, randExponential, randPoisson, randLogNormal, randBernoulli and others) alongside the existing uniform randCanonical and randUniform. Combined with numbers(), these functions can populate MergeTree tables with realistic test data: exponentially distributed purchase totals, Poisson-distributed event timestamps peaking at midday, binomially shaped CPU metrics with noise, multi-modal seasonal peaks, weighted enum values and random strings. Use floor() rather than round() to get uniformly distributed integers, because rounding under-samples the range edges.
- ClickHouse Newsletter November 2022: The purifying effects of obfuscation
ClickHouse mediumAdept
ClickHouse Cloud pricing now charges only for compute and storage, and ClickHouse 22.10 adds S3 backups (full and incremental), `SET setting = DEFAULT`, forced merging of old parts via `min_age_to_force_merge_seconds`, a relaxed too-many-parts check for large partitions, new random-distribution functions and a preview Kafka Connect sink with exactly-once semantics. The featured query shows how `clickhouse-obfuscator` turns a real dataset, demonstrated on 26.7M UK property sales in Parquet, into synthetic data that keeps row count, cardinality and value distributions close to the original. That matters for realistic GROUP BY memory and performance testing, but the output is neither encrypted nor hashed and is not automatically safe to share. Also covered: upcoming meetups and webinars, plus links to migration stories and tuning posts.