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.

SqlData Fetching

Code

snippet
-- 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

FAQ

Which tables does the SQL touch?
The references are `users`.