Sampling function
Updated at:
The SAMPLE clause lets you query a random subset of a table instead of scanning the full dataset — useful for exploratory analysis, testing, or quick aggregations on large tables.
Syntax
SAMPLE [BLOCK] (sample_percent[, dummy_arg]) [SEED (seed_value)]Parameters
| Parameter | Required | Description |
|---|---|---|
BLOCK | Optional | Changes the sampling unit from row to block. Without BLOCK, the basic unit of sampling is row. With BLOCK, the basic unit of sampling is block, meaning all data or no data in a block is selected. |
sample_percent | Required | The target percentage of data to sample from the source table. Valid values: [0, 100]. This value represents a probability, not an exact count — the actual number of rows returned varies each run and approximates sample_percent% of the total. |
dummy_arg | Optional | A compatibility parameter with no effect on results. If specified, the value must be ≥ 1. |
seed_value | Optional | A random seed for reproducible sampling. Given the same seed and the same other parameters, the query returns the same rows every time. |
Return value
A subset of the source table. The number of rows returned is less than or equal to the total rows in the table, and approximates sample_percent% of the total.
Examples
Set up a sample table with 10,001 rows:
CREATE TABLE sample_table_test (id int, name text);
INSERT INTO sample_table_test
SELECT i, repeat(i::text, 10) FROM generate_series(0, 10000) s(i);Block sampling with a fixed seed
Sample approximately 10% of rows using block sampling. Setting seed_value to 10 makes the result reproducible.
SELECT COUNT(*) FROM sample_table_test SAMPLE BLOCK (10, 1) SEED (10);
-- Returns: 873 (result is reproducible)Row sampling without a seed
Sample approximately 5% of rows using row sampling. Without a seed, the result varies each run.
SELECT COUNT(*) FROM sample_table_test SAMPLE (5);
-- Returns: 485 (result varies each run)Is this page helpful?