TABLESAMPLE BERNOULLI And SYSTEM Sampling
TABLESAMPLE BERNOULLI flips a coin per row while SYSTEM samples whole pages; REPEATABLE seeds both so repeated runs return the exact same rows.
Code
-- BERNOULLI:逐行掷硬币,独立按概率抽行,分布均匀
SELECT id, region
FROM events TABLESAMPLE BERNOULLI (10) REPEATABLE (42);
-- SYSTEM:按数据页整块抽,更快,但抽样单位是页,行可能聚集
SELECT id, region
FROM events TABLESAMPLE SYSTEM (10) REPEATABLE (42);
-- REPEATABLE (seed):同一种子重复执行返回完全相同的行
SELECT count(*) AS sampled_rows
FROM events TABLESAMPLE BERNOULLI (50) REPEATABLE (7);
-- WHERE 在抽样之后执行:先抽 10%,再从样本里过滤大额行
SELECT id, region
FROM events TABLESAMPLE BERNOULLI (10) REPEATABLE (42)
WHERE amount_cents > 100000;
-- 百分比是"大约":两种方式都不保证精确行数How the snippet works
What runs here is SELECT — events are the objects involved.
What the statements actually assemble: a WHERE clause that keeps only the rows a statement is meant to touch; COUNT aggregation.
Applying it
Point it at the events table.
Statements that matter
SELECT id, region
FROM events TABLESAMPLE BERNOULLI (10) REPEATABLE (42)
WHERE amount_cents > 100000;
SELECT count(*) AS sampled_rows
FROM events TABLESAMPLE BERNOULLI (50) REPEATABLE (7);
SELECT id, region
FROM events TABLESAMPLE BERNOULLI (10) REPEATABLE (42);
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- What objects does the SQL involve?
- `events` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.