0Pricing
Advanced PostgreSQL: Indexing, Partitioning, Replication · Урок

Отсечение и исключение секций

Подробно изучите, как оптимизатор использует ключи секционирования для исключения нерелевантных секций и значительного сокращения объёма просматриваемых данных.

«Отсечение и исключение секций» — бесплатный урок Advanced PostgreSQL: Indexing, Partitioning, Replication на CoddyKit. Это урок 3 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Advanced PostgreSQL: Indexing, Partitioning, Replication, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Advanced PostgreSQL: Indexing, Partitioning, Replication содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

What is Partition Pruning?

Welcome to a key optimization technique in PostgreSQL: Partition Pruning. This is where the database intelligently skips scanning partitions that cannot possibly contain the data a query is looking for.

Think of it as filtering bookshelves: if you're looking for a book published in 2023, you wouldn't check shelves marked '1990-1999' or '2000-2010'.

How the Optimizer Works

When you execute a query on a partitioned table, PostgreSQL's query planner examines the WHERE clause. It compares the conditions in your query to the definitions of your table's partitions.

If the query's conditions guarantee that certain partitions cannot possibly hold any matching rows, the optimizer simply excludes those partitions from the scan plan. This significantly reduces the amount of data that needs to be read from disk.

Pruning with Range Partitions

Partition pruning is most evident with range-partitioned tables, especially those partitioned by date or timestamp. For example, if you have a table partitioned by month, and you query for data from a specific week, only the relevant month partition(s) will be scanned.

This is incredibly powerful for time-series data, as queries often target specific timeframes.

Demo: Range Pruning in Action

Let's create a simple range-partitioned table and see how EXPLAIN shows pruning. We'll partition by sale_date.

Notice how the EXPLAIN output will only show a scan on the relevant partition, not the others.

CREATE TABLE sales (
    sale_id INT,
    sale_date DATE,
    amount NUMERIC
) PARTITION BY RANGE (sale_date);

CREATE TABLE sales_2023_q1 PARTITION OF sales
FOR VALUES FROM ('2023-01-01') TO ('2023-04-01');

CREATE TABLE sales_2023_q2 PARTITION OF sales
FOR VALUES FROM ('2023-04-01') TO ('2023-07-01');

INSERT INTO sales VALUES (1, '2023-01-15', 100);
INSERT INTO sales VALUES (2, '2023-04-20', 200);

EXPLAIN SELECT * FROM sales WHERE sale_date = '2023-01-15';

Pruning with List Partitions

Partition pruning also works effectively with list-partitioned tables. If your table is partitioned by a discrete value, like a region or a status code, and your query filters on that specific value, only the corresponding partition will be scanned.

This is useful when you often query data specific to certain categories or groups.

Demo: List Pruning Example

Here's an example using a list-partitioned table based on a region column. Observe the EXPLAIN output to see only the 'North' partition being scanned.

CREATE TABLE products (
    product_id INT,
    region TEXT,
    price NUMERIC
) PARTITION BY LIST (region);

CREATE TABLE products_north PARTITION OF products
FOR VALUES IN ('North');

CREATE TABLE products_south PARTITION OF products
FOR VALUES IN ('South');

INSERT INTO products VALUES (101, 'North', 50.00);
INSERT INTO products VALUES (102, 'South', 75.00);

EXPLAIN SELECT * FROM products WHERE region = 'North';

Static vs. Dynamic Pruning

PostgreSQL employs two main types of pruning:

  • Static Pruning: Occurs at query planning time. The planner can see the explicit values in your WHERE clause and immediately exclude partitions.
  • Dynamic Pruning: Happens during query execution. This is for more complex cases, like when the partition key is filtered by the result of a subquery or a parameter from a join. The database determines which partitions to scan as it runs.

When Pruning Might Not Occur

While powerful, partition pruning isn't always possible:

  • Complex Expressions: If your WHERE clause uses a function or complex expression on the partition key (e.g., EXTRACT(MONTH FROM sale_date) = 1).
  • Non-Partition Key Filters: Queries filtering only on columns not part of the partition key will scan all partitions.
  • Joins: Pruning with joins can be trickier, especially if the join condition doesn't directly involve the partition key or if the values are not known until runtime.

Verifying Pruning with EXPLAIN

To confirm that partition pruning is working, always use EXPLAIN (or EXPLAIN ANALYZE). Look for lines like:

  • -> Partition Selector (Dyanmic Partition Pruning)
  • -> Append (partitions: 1)
  • -> Result (partitions: 1)

The key is seeing a limited number of partitions selected, rather than scanning the entire partitioned table or all its child tables.

Quick Check: Pruning Benefits

Understanding partition pruning is crucial for optimizing queries on large partitioned tables. Let's test your knowledge!

Pruning Power-Up!

You've mastered partition pruning! You now understand that it's a vital PostgreSQL optimization that:

  • Significantly reduces the amount of data scanned.
  • Works by comparing WHERE clauses with partition definitions.
  • Is especially effective with range and list partitions.
  • Can be static (planning time) or dynamic (execution time).
  • Can be verified using EXPLAIN.

By leveraging partition pruning, you ensure your queries run as efficiently as possible on large datasets!

Часто задаваемые вопросы

Урок «Отсечение и исключение секций» бесплатный?

Да — полный текст урока «Отсечение и исключение секций» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Advanced PostgreSQL: Indexing, Partitioning, Replication, подпишись на CoddyKit PRO. Курс Advanced PostgreSQL: Indexing, Partitioning, Replication содержит 4 уроков всего.

Чему я научусь в уроке «Отсечение и исключение секций»?

Подробно изучите, как оптимизатор использует ключи секционирования для исключения нерелевантных секций и значительного сокращения объёма просматриваемых данных. Ты практикуешь Advanced PostgreSQL: Indexing, Partitioning, Replication с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Advanced PostgreSQL: Indexing, Partitioning, Replication?

Предыдущий опыт не требуется. Advanced PostgreSQL: Indexing, Partitioning, Replication на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 3 из 4.

Сколько времени занимает урок «Отсечение и исключение секций»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Advanced PostgreSQL: Indexing, Partitioning, Replication?

Да. Каждый урок Advanced PostgreSQL: Indexing, Partitioning, Replication включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Оптимизация запросов с помощью секционирования
  2. Подключение и отключение секций
  3. Отсечение и исключение секций
  4. Соединения и агрегации по секциям
← Назад к Advanced PostgreSQL: Indexing, Partitioning, Replication