21.3. Выборка данных #

В этом разделе описывается, как выполнять выборку данных.

21.3.1. Оценка количества уникальных значений (approx_count_distinct) #

Хранимая процедура approx_count_distinct использует алгоритм HyperLogLog для оценки количества уникальных значений. Для больших наборов данных это работает быстрее, чем агрегатная функция COUNT(DISTINCT), но результат имеет небольшую погрешность.

Требуемые права: суперпользователь или администратор Postgres Pro AXE.

За подробной информацией об управлении доступом обратитесь к Главе 12.

Выполните следующую команду на сервере Postgres Pro AXE:

    SELECT approx_count_distinct(выражение) FROM источник;
  

Где:

  • выражение: выражение, количество уникальных значений которого требуется оценить.

  • источник: источник выражения, например аналитическая таблица, хранимая процедура read_parquet или подзапрос.

Postgres Pro AXE вернёт оценку количества уникальных значений в виде значения BIGINT.

Пример 21.25. Оценка количества уникальных значений

Оценка количества уникальных значений в столбце customer_id таблицы orders:

    SELECT approx_count_distinct(customer_id) AS approx_distinct
    FROM orders;
  
    approx_distinct
    -----------------
            1234
  

По сравнению с агрегатной функцией COUNT(DISTINCT):

    SELECT COUNT(DISTINCT customer_id) AS exact_distinct
    FROM orders;
  
    exact_distinct
    ----------------
          1237
  

21.3.2. Выборка строк таблицы (TABLESAMPLE) #

Хранимая процедура TABLESAMPLE возвращает подмножество строк из аналитической таблицы. Это полезно для предварительного анализа данных, профилирования данных, а также тестирования производительности на больших наборах данных.

Требуемые права: суперпользователь или администратор Postgres Pro AXE для аналитических таблиц. Для таблиц-куч — право SELECT на таблицу.

За подробной информацией об управлении доступом обратитесь к Главе 12.

Выполните следующую команду на сервере Postgres Pro AXE:

    SELECT * FROM таблица TABLESAMPLE метод_выборки(процент);
  

Где:

  • таблица: аналитическая таблица, из которой требуется извлечь выборку строк.

  • способ_выборки: метод извлечения выборки.

    Возможные значения:

    • SYSTEM: случайная выборка на уровне хранилища.

      Этот способ работает быстрее, но возвращает приблизительно запрошенный процент.

    • BERNOULLI: построчная случайная выборка.

      Этот способ работает медленнее, но возвращает точно запрошенный процент.

  • процент: процент строк от 0 до 100.

Postgres Pro AXE вернёт выбранные строки.

Пример 21.26. Выборка строк таблицы

Выборка 10% строк из аналитической таблицы orders с использованием метода SYSTEM:

    SELECT * FROM orders TABLESAMPLE SYSTEM(10);
  

Выборка 5% строк с использованием метода BERNOULLI:

    SELECT * FROM orders TABLESAMPLE BERNOULLI(5);
  

Профилирование данных на основе 2% выборки:

    SELECT
      status,
      COUNT(*) AS sample_count,
      AVG(amount) AS avg_amount
    FROM orders TABLESAMPLE SYSTEM(2)
    GROUP BY status;
  

Выборка строк при объединении с таблицей customers:

    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;
  

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, a read_parquet stored 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;
  

FAQ