0Pricing
Advanced PostgreSQL: Indexing, Partitioning, Replication · Leçon

Élagage et exclusion des partitions

Approfondissez la manière dont l’optimiseur utilise les clés de partition pour exclure les partitions inutiles et réduire considérablement le volume de données analysé.

Élagage et exclusion des partitions est une leçon Advanced PostgreSQL: Indexing, Partitioning, Replication gratuite sur CoddyKit. Ceci est la leçon 3 sur 4. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage Advanced PostgreSQL: Indexing, Partitioning, Replication, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours Advanced PostgreSQL: Indexing, Partitioning, Replication comprend 4 leçons au total.

Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.

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!

Questions Fréquemment Posées

La leçon « Élagage et exclusion des partitions » est-elle gratuite ?

Oui — le texte complet de « Élagage et exclusion des partitions » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours Advanced PostgreSQL: Indexing, Partitioning, Replication, passe à CoddyKit PRO. Le cours Advanced PostgreSQL: Indexing, Partitioning, Replication comprend 4 leçons au total.

Qu'est-ce que j'apprendrai dans « Élagage et exclusion des partitions » ?

Approfondissez la manière dont l’optimiseur utilise les clés de partition pour exclure les partitions inutiles et réduire considérablement le volume de données analysé. Tu pratiques Advanced PostgreSQL: Indexing, Partitioning, Replication avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.

Dois-je avoir de l'expérience pour commencer Advanced PostgreSQL: Indexing, Partitioning, Replication ?

Aucune expérience préalable n'est requise. Advanced PostgreSQL: Indexing, Partitioning, Replication sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 3 sur 4.

Combien de temps prend la leçon « Élagage et exclusion des partitions » ?

La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.

Peux-tu écrire et exécuter du code dans cette leçon Advanced PostgreSQL: Indexing, Partitioning, Replication ?

Oui. Chaque leçon Advanced PostgreSQL: Indexing, Partitioning, Replication inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.

Toutes les leçons de ce cours

  1. Optimisation des requêtes avec le partitionnement
  2. Attacher et détacher des partitions
  3. Élagage et exclusion des partitions
  4. Jointures et agrégations par partition
← Retour à Advanced PostgreSQL: Indexing, Partitioning, Replication