TABLESAMPLE SYSTEM Versus BERNOULLI
Sample rows cheaply with TABLESAMPLE SYSTEM for block-level speed or BERNOULLI for row-level evenness, pinning the draw with REPEATABLE.
Code
-- TABLESAMPLE 不扫描全表,代价远低于 ORDER BY random() LIMIT n
-- SYSTEM:按数据块采样,速度快但同块内的行要么全中要么全不中
SELECT id, email FROM users
TABLESAMPLE SYSTEM (10); -- 约 10% 的块
-- BERNOULLI:按行独立采样,结果更均匀但要读更多块
SELECT id, email FROM users
TABLESAMPLE BERNOULLI (5); -- 约 5% 的行
-- REPEATABLE 固定采样种子:同一数据集重跑得到完全相同的样本
SELECT id, email FROM users
TABLESAMPLE BERNOULLI (5) REPEATABLE (42);
-- 采样比例是近似的:SYSTEM 按块计,BERNOULLI 每行独立掷骰
SELECT count(*) FROM users TABLESAMPLE SYSTEM (10);What the code does
Several statements share this file — SELECT, with users among the objects involved.
Breaking the statements into their working parts: COUNT aggregation.
Applying it
Run the statement against the users table.
Statements that matter
SELECT id, email FROM users
TABLESAMPLE SYSTEM (10); -- 约 10% 的块
SELECT id, email FROM users
TABLESAMPLE BERNOULLI (5); -- 约 5% 的行
SELECT id, email FROM users
TABLESAMPLE BERNOULLI (5) REPEATABLE (42);
SELECT count(*) FROM users TABLESAMPLE SYSTEM (10);
Interactive Tools for This Topic
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.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.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
- Which tables does the SQL touch?
- The references are `users`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.