Partition Pruning & Elimination
Partition Your Data
Partitioning splits a large table into smaller, physically separate pieces based on a key. When you query with a filter on the partition key, the database eliminates partitions that don't match â scanning only relevant data.
- Range Partitioning â By date ranges (most common)
- Hash Partitioning â Even distribution by hash value
- List Partitioning â By categorical values (region, status)
- Partition Pruning â WHERE clause eliminates irrelevant partitions
Partitioning is essential for tables with billions of rows â it turns a 10-minute full table scan into a 1-second partition scan.
Partition Types Visualized
Range Partitioning
-- PostgreSQL declarative partitioning
CREATE TABLE orders (
order_id BIGINT,
customer_id INT,
order_date DATE,
total_amount DECIMAL(10,2)
) PARTITION BY RANGE (order_date);
-- Create quarterly partitions
CREATE TABLE orders_2023_q1 PARTITION OF orders
FOR VALUES FROM ('2023-01-01') TO ('2023-04-01');
CREATE TABLE orders_2023_q2 PARTITION OF orders
FOR VALUES FROM ('2023-04-01') TO ('2023-07-01');
CREATE TABLE orders_2023_q3 PARTITION OF orders
FOR VALUES FROM ('2023-07-01') TO ('2023-10-01');
CREATE TABLE orders_2023_q4 PARTITION OF orders
FOR VALUES FROM ('2023-10-01') TO ('2024-01-01');
âšī¸
Key Insight: Partition pruning automatically eliminates partitions that don't match the query's WHERE clause. This dramatically reduces I/O by only scanning relevant partitions â from scanning 100GB to scanning 25GB for a quarterly query.
When Pruning Actually Happens
Pruning is a planning decision, not a runtime filter. When you run EXPLAIN on a range predicate over order_date, PostgreSQL evaluates each partition's constraint against that predicate and drops the non-matching partitions from the plan entirely. They appear in neither the plan tree nor the execution statistics, and their indexes are never opened, so the saving is complete rather than proportional.
Parameterised statements complicate the picture. When a prepared statement binds its value only at execution, PostgreSQL defers part of the pruning (available since version 11): the plan carries a one-time filter and removes partitions as the parameter arrives. Repeated calls with different dates can therefore produce different partition sets for the same prepared statement, which shows up in EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) as a reduced count of partitions removed.
Worked Numbers: What a Pruned Scan Saves
A 100 GB orders table split into 40 quarterly partitions holds roughly 2.5 GB per partition. A query for one quarter reads 2.5 GB instead of 100 GB, a 40Ã reduction in I/O, and each partition carries its own smaller B-tree â a few hundred megabytes instead of tens of gigabytes, which usually fits inside shared_buffers and turns random reads into cache hits. Maintenance gains more than the queries do: deleting expired rows becomes DROP TABLE orders_2019_q1, a metadata operation taking milliseconds, instead of a purge that generates hundreds of millions of dead tuples and keeps autovacuum busy for hours.
The countervailing cost is planning. PostgreSQL locks and checks one constraint per partition while building the plan, so a table with 10,000 partitions can spend longer planning than executing a short query. Production guidance settles around a few hundred partitions per table, extending to a few thousand only when every query is known to hit a narrow slice.
Hash Partitioning
-- Hash partitioning for even distribution
CREATE TABLE users (
user_id BIGINT,
username VARCHAR(100),
email VARCHAR(255)
) PARTITION BY HASH (user_id);
CREATE TABLE users_p0 PARTITION OF users FOR VALUES WITH (MODULUS 4, REMAINDER 0);
CREATE TABLE users_p1 PARTITION OF users FOR VALUES WITH (MODULUS 4, REMAINDER 1);
CREATE TABLE users_p2 PARTITION OF users FOR VALUES WITH (MODULUS 4, REMAINDER 2);
CREATE TABLE users_p3 PARTITION OF users FOR VALUES WITH (MODULUS 4, REMAINDER 3);
List Partitioning
-- List partitioning for categorical data
CREATE TABLE sales (
sale_id BIGINT,
region VARCHAR(50),
amount DECIMAL(10,2)
) PARTITION BY LIST (region);
CREATE TABLE sales_us PARTITION OF sales FOR VALUES IN ('US_EAST', 'US_WEST');
CREATE TABLE sales_eu PARTITION OF sales FOR VALUES IN ('EU_WEST', 'EU_EAST');
CREATE TABLE sales_apac PARTITION OF sales FOR VALUES IN ('APAC_EAST', 'APAC_WEST');
BigQuery Partitioning
-- BigQuery time-unit partitioning
CREATE TABLE `project.dataset.events` (
event_id STRING, event_time TIMESTAMP,
user_id STRING, event_type STRING
)
PARTITION BY DATE(event_time)
OPTIONS (require_partition_filter = true);
-- Query with partition filter (required!)
SELECT * FROM `project.dataset.events`
WHERE event_time >= '2024-01-01' AND event_time < '2024-02-01';
â ī¸
Important: BigQuery's require_partition_filter = true forces queries to include a partition filter, preventing full-table scans and reducing costs. Without it, you scan the entire table and pay for all data.
Partition Pruning Patterns
The rewrite in this block is the most common pruning bug in real code. A predicate that wraps the partition column in a function is opaque to the constraint checker: EXTRACT(YEAR FROM order_date) = 2023 can be satisfied by rows living in any partition, so the planner keeps every partition and the query degrades into a full scan of forty partitions to answer a one-partition question. PostgreSQL does not evaluate the function symbolically, and neither does MySQL or Oracle.
BigQuery is the exception that proves the rule. WHERE DATE(event_time) = '2024-01-15' does prune there, because the partition column expression is part of the table definition and the engine recognizes the transformation; written against a PostgreSQL partition key, the identical shape never prunes. When a query crosses engines, re-test pruning with EXPLAIN, by reading the partitions eliminated in the plan, or by watching Bytes Billed â never assume the predicate transfers.
-- Good: Pruning works
SELECT * FROM orders WHERE order_date = '2023-06-15';
-- Good: Range pruning
SELECT * FROM orders
WHERE order_date BETWEEN '2023-04-01' AND '2023-06-30';
-- Bad: Pruning fails (function on partition column)
SELECT * FROM orders WHERE EXTRACT(YEAR FROM order_date) = 2023;
-- Good: Rewrite for pruning
SELECT * FROM orders
WHERE order_date >= '2023-01-01' AND order_date < '2024-01-01';
Too Many Partitions Is Also a Bug
Over-partitioning fails in ways that look like random slowness rather than a design choice. The symptoms are distinctive: planning time growing in proportion to partition count, thousands of rows in pg_locks after a DDL change, autovacuum that never finishes because it keeps rotating through small partitions, and catalog queries against pg_class that suddenly take seconds. Rules that hold up in production: partition on the column that dominates the predicate, size each partition so it holds at least a few hundred megabytes, pre-create the future range you will need, keep a DEFAULT partition as a safety net, and prefer dropping a partition to deleting its rows.
| Partitions per table | Planning overhead | Maintenance | When it fits |
|---|---|---|---|
| 12 (monthly, one year) | Negligible | Trivial | Small and medium tables |
| 40 (quarterly, a decade) | Low | Batch drop of old ranges | Typical analytics tables |
| 500 (daily, multi-year) | Measurable per query | Automation required | Event logs with narrow filters |
| 10,000 (per user or hash bucket) | Planning dominates the query | Unmanageable | Almost never; use clustering instead |
đĄSizing rule
Estimate partition count as retention window divided by time slice, never as rows divided by target rows. Time slices are predictable, row counts drift with traffic, and a fixed layout becomes a maintenance treadmill the moment traffic doubles.
Composite Partitioning (Subpartitioning)
-- First level: by date
CREATE TABLE orders_2023 PARTITION OF orders
FOR VALUES FROM ('2023-01-01') TO ('2024-01-01')
PARTITION BY LIST (region);
-- Second level: by region within year
CREATE TABLE orders_2023_us PARTITION OF orders_2023
FOR VALUES IN ('US_EAST', 'US_WEST');
Partition Maintenance
-- Create new partition in advance
CREATE TABLE orders_2024_q1 PARTITION OF orders
FOR VALUES FROM ('2024-01-01') TO ('2024-04-01');
-- Detach old partition
ALTER TABLE orders DETACH PARTITION orders_2022_q1;
-- Drop old partition
DROP TABLE orders_2022_q1;
-- Default partition catches unmatched rows
CREATE TABLE orders_default PARTITION OF orders DEFAULT;
Engine Differences Worth Memorizing
Interviewers reach for this comparison because it separates people who have run the systems from people who have only read about them.
| Engine | Pruning trigger | Function on the key | Filter forced | Distinguishing behaviour |
|---|---|---|---|---|
| PostgreSQL 10 and later | Constraint at plan time, plus runtime for bound parameters | Blocks pruning | No | enable_partition_pruning defaults to on |
| MySQL 8 | Range predicate on the partition column | Blocks pruning | Effectively yes | Queries should name the partition column |
| Oracle | Automatic at plan time | A few forms understood | No | Interval partitions create the next range on insert |
| BigQuery | Partition column predicate | DATE() prunes | Optional via require_partition_filter | Billing follows partitions scanned, so pruning is a cost control |
| SQL Server | Predicate against the partition function | Blocks pruning | No | Reports partition elimination in the plan |
The BigQuery row is the one that surprises people: a function over the partition timestamp is legal there and still prunes, and turning on require_partition_filter converts a forgotten predicate into a query error instead of an unexpected invoice.
Quiz: Test Your Knowledge
Follow-Up Questions
- When would you choose hash partitioning over range partitioning?
- How does partition pruning interact with index usage?
- What's the impact of partitioning on INSERT performance?
- How do you handle cross-partition queries efficiently?
- Explain the concept of partition elimination in distributed databases.
Key Takeaways
- Range partitioning â Best for date/time columns (quarterly, monthly)
- Hash partitioning â Even distribution for point lookups (no range queries)
- List partitioning â Categorical columns (region, status)
- Partition pruning â WHERE clause must reference partition column directly (no functions!)
- Default partition â Catches unmatched rows to prevent INSERT errors
- BigQuery â Use
require_partition_filter = trueto prevent full-table scans
Common Mistakes
Wrapping the partition key in a function, so the planner keeps every partition in the plan
Fix: Express a range on the key itself and re-run EXPLAIN to confirm partitions were actually removed
Creating thousands of tiny partitions and then blaming the engine for slow planning
Fix: Size by time slice with a few hundred partitions at most, and drop ranges instead of deleting rows
Assuming a DATE() predicate prunes everywhere because it does on BigQuery
Fix: Verify per engine: EXPLAIN for PostgreSQL, partition elimination for SQL Server, Bytes Billed for BigQuery
Letting inserts fall into the DEFAULT partition because the next range was never created
Fix: Schedule pre-creation ahead of each boundary and alert on rows that land in DEFAULT