liveBook · Manning

Partition pruning

As explained in PostgreSQL Mistakes and How to Avoid Them

Partition pruning is the query-planning technique of excluding table partitions that cannot contain rows matching the query conditions.

Partition pruning excludes partitions that cannot contain matching rows. PostgreSQL can do this when a query predicates on the partition key, reducing the data it must scan. section 4.2

Time-partitioned payments

Partition a payments table by RANGE on tstamp into monthly partitions. A query for one timestamp scans only payments_p_2022_3 instead of the entire table; the demonstrated runtime falls from about 62 seconds to 2.5 seconds.

Use the query plan to verify pruning:

  • Include the partition key in the predicate; otherwise the planner cannot exclude partitions based on that condition. section 4.2
  • Treat pruning as a complement to partitioning: smaller scans help performance, while dropping a whole old partition simplifies maintenance. section 4.2

How PostgreSQL Mistakes and How to Avoid Them covers it

How deep it goes
Demonstrates RANGE partitioning, monthly partitions, EXPLAIN verification, measured runtimes, and the requirement to predicate on the key.
Examples
Uses monthly payments partitions, timestamp lookup plans, buffer counts, runtimes, bulk loading, and dropping an obsolete partition.
What it assumes
Assumes SQL and PostgreSQL query-plan familiarity while demonstrating partition creation and pruning behavior.
What you can do after
Diagnose pruning with EXPLAIN (ANALYZE, BUFFERS) and write predicates that let PostgreSQL exclude irrelevant partitions.
How it connects
Connects partition pruning with table partitioning, RANGE partitioning, partition keys, and query planning.

Also explained in

Compare how 3 books explain partition pruning →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of PostgreSQL Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.