Partition Pruning in PostgreSQL: What It Is and How It Works
partition pruning is a technique that skips scanning unnecessary partitions in a partitioned table during query execution. It improves performance by only accessing relevant partitions based on query conditions.How It Works
Partition pruning works like choosing which drawers to open in a filing cabinet instead of searching through every drawer. When you run a query on a partitioned table, PostgreSQL looks at the query's conditions and decides which partitions could contain matching data.
It then skips the partitions that cannot have relevant rows, saving time and resources. This is done during query planning or execution, depending on the PostgreSQL version and query type.
Example
This example shows how partition pruning works with a table partitioned by a date column. The query only scans the partition for the specified date.
CREATE TABLE sales ( id SERIAL PRIMARY KEY, sale_date DATE NOT NULL, amount NUMERIC ) PARTITION BY RANGE (sale_date); CREATE TABLE sales_2023 PARTITION OF sales FOR VALUES FROM ('2023-01-01') TO ('2024-01-01'); CREATE TABLE sales_2024 PARTITION OF sales FOR VALUES FROM ('2024-01-01') TO ('2025-01-01'); INSERT INTO sales (sale_date, amount) VALUES ('2023-06-15', 100), ('2024-03-10', 200); EXPLAIN ANALYZE SELECT * FROM sales WHERE sale_date = '2023-06-15';
When to Use
Use partition pruning when working with large partitioned tables to speed up queries that filter on the partition key. It is especially helpful for time-series data, logs, or any data split by ranges or lists.
This reduces disk I/O and CPU usage by avoiding scanning irrelevant partitions, making queries faster and more efficient.
Key Points
- Partition pruning skips scanning partitions that cannot match query filters.
- It improves query speed and reduces resource use.
- Works best when queries filter on the partition key.
- Supported in PostgreSQL 11 and later with improvements in newer versions.