21.3. Data Sampling #
This section describes how to sample data.
21.3.1. Estimating the Number of Distinct Values (approx_count_distinct) #
The approx_count_distinct stored procedure uses the HyperLogLog algorithm to count distinct values. This is faster than the COUNT(DISTINCT) aggregate, but the result has some error rate.
Required privileges: Superuser or the Postgres Pro AXE administrator.
For more information about access management, refer to Chapter 12.
Execute the following command on the Postgres Pro AXE server:
SELECT approx_count_distinct(expression) FROM source;
Where:
expression: The expression whose distinct values must be estimated.source: The source of the expression, e.g., an analytical table, aread_parquetstored procedure, or a subquery.
Postgres Pro AXE will return an estimate of the number of distinct values as a BIGINT value.
Example 21.25. Estimating the Number of Distinct Values
Estimating the number of distinct values in the customer_id column of the orders table:
SELECT approx_count_distinct(customer_id) AS approx_distinct
FROM orders;
approx_distinct
-----------------
1234
As compared to the COUNT(DISTINCT) aggregate:
SELECT COUNT(DISTINCT customer_id) AS exact_distinct
FROM orders;
exact_distinct
----------------
1237
21.3.2. Sampling Table Rows (TABLESAMPLE) #
The TABLESAMPLE stored procedure returns a subset of rows from an analytical table. This is useful for exploratory data analysis, data profiling, and performance testing on large datasets.
Required privileges: Superuser or the Postgres Pro AXE administrator for analytical tables. For heap tables — the SELECT privilege on the table.
For more information about access management, refer to Chapter 12.
Execute the following command on the Postgres Pro AXE server:
SELECT * FROM table TABLESAMPLE sampling_method(percentage);
Where:
table: The analytical table from which rows must be sampled.sampling_method: The sampling method.Possible values:
SYSTEM: Random sampling at the storage level.This method is faster but returns the requested percentage approximately.
BERNOULLI: Row-by-row random sampling.This method is slower but returns the requested percentage exactly.
percentage: The percentage of rows from 0 to 100.
Postgres Pro AXE will return the sampled rows.
Example 21.26. Sampling Table Rows
Sampling 10% of rows from the orders analytical table using the SYSTEM method:
SELECT * FROM orders TABLESAMPLE SYSTEM(10);
Sampling 5% of rows using the BERNOULLI method:
SELECT * FROM orders TABLESAMPLE BERNOULLI(5);
Profiling data with a 2% sample:
SELECT
status,
COUNT(*) AS sample_count,
AVG(amount) AS avg_amount
FROM orders TABLESAMPLE SYSTEM(2)
GROUP BY status;
Sampling rows in a join with the customers table:
SELECT c.name, COUNT(o.id) AS order_count
FROM customers c
JOIN orders o TABLESAMPLE SYSTEM(10) ON c.id = o.customer_id
GROUP BY c.name;