How to take random samples from big PostgreSQL tables
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.
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.
- Native random sampling in ClickHouse
ClickHouse mediumAdept
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.
- 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.
- PostgresBench: A Reproducible Benchmark for Postgres Services
ClickHouse mediumAdept
PostgresBench is an open, reproducible benchmark for managed Postgres services built on pgbench's TPC-B-like workload (256 clients, 16 threads, 10-minute runs, three runs each) at ~100 GB and ~500 GB scale factors, with default configs, HA disabled and all services in us-east-2. In the first cohort, ClickHouse's NVMe-backed managed Postgres reached about 28.7K TPS on 16 vCPU/64 GB at 100 GB, versus 14.8K for Crunchy Bridge, 12.6K for Aurora, 8.6K for Neon and 8.1K for RDS, and held about 26K TPS at 500 GB. ClickHouse attributes the lead to co-located local NVMe storage, which avoids network round trips on every fsync and WAL commit in write-heavy workloads. Scripts and raw JSON results are on GitHub for verification and community submissions, though the vendor-run setup and absence of pricing comparisons are worth weighing.
- Implementing "seen by" functionality with Postgres
Supabase mediumAdeptFour ways to track post views in Postgres are benchmarked: a naive counter column, an hstore of viewer IDs per post, an association table, and the HyperLogLog extension. HyperLogLog is the recommended default because its tradeoffs are good and it adds no large architectural liabilities. hstore is fine for a quick prototype and performed best with integer IDs. The benchmark uses synthetic users and posts with an 80/20 poster skew, replayed through autocannon with a 10/60/30 mix of list-viewers, read-count and record-view requests.