Partitioning is a physical design decision, not a tuning knob
A partitioned table is one table presented to the user and many storage objects underneath, each holding a declared slice of the rows. The optimiser's job is to work out which slices a query can possibly touch and to open only those. When that works, a query over a year of history reads a single day's data and finishes in milliseconds; when it does not, the same query opens every partition and performs worse than an unpartitioned table would have, because the engine now also has to plan around the split.
Everything follows from the match between your partition key and your predicates. A table partitioned by order_date answers daily questions cheaply and monthly questions reasonably, while a query filtering on customer_id alone gets no benefit at all. That is why partitioning is a workload decision: you need to know which columns appear in the WHERE clause of the dominant queries before you declare a key.
By the end of this lesson you should be able to read a plan and tell whether pruning happened, choose a composite scheme that matches a two-dimensional access pattern, and schedule the maintenance that keeps partitions healthy without locking the table.
Range, list, hash, and what each prunes
Each partitioning method answers a different question about selectivity, and choosing the wrong one is the most common cause of a partitioned table that never prunes.
| Method | Slices rows by | Prunes when | Weakness | Typical use |
|---|---|---|---|---|
| Range | Ordered value intervals | Comparisons on the key | Gaps and overflows need handling | Time, ids, amounts |
| List | Explicit value sets | Equality on the key | Cardinality must be finite | Region, status, tenant |
| Hash | Hash of key across N buckets | Equality on the key | No range support | Even distribution, tenant isolation |
| Composite range-list | Range then list | Both predicates present | More objects to manage | Month per region |
| Composite list-hash | List then hash | Equality on both | Similar complexity | Tenant then shard |
| Reference | Child rows matching parent key | Joins on the parent | Parent size limits children | Large child tables |
Two subtleties matter in practice. Range partitions need a catch-all destination â an explicit maximum bound, an interval partition, or a default partition â or the first row outside your declared range fails the insert at 02:00 with no one watching. Hash partitions give excellent distribution but zero pruning for anything other than equality on the key, so they solve skew, not query latency; teams that reach for hash to fix slow queries usually fix throughput while leaving latency untouched.
Composite subpartitioning without regret
Subpartitioning exists when one dimension is not enough: monthly range partitions are useful for retention, but each month also needs regional slices for a tenant that queries one region at a time. The engine partitions each first-level partition again, producing a grid of storage objects.
-- Range by month, then list by region within each month
CREATE TABLE events (
event_id bigint NOT NULL,
event_time timestamp NOT NULL,
region varchar(10) NOT NULL,
tenant_id bigint NOT NULL,
payload jsonb NOT NULL
)
PARTITION BY RANGE (event_time)
SUBPARTITION BY LIST (region)
SUBPARTITION TEMPLATE (
PARTITION p_emea VALUES IN ('EU', 'UK', 'MEA'),
PARTITION p_amer VALUES IN ('US', 'CA', 'LATAM'),
PARTITION p_apac VALUES IN ('JP', 'AU', 'SG', 'IN'),
PARTITION p_other DEFAULT
);
CREATE TABLE events_2026_03 PARTITION OF events
FOR VALUES FROM ('2026-03-01') TO ('2026-04-01')
PARTITION BY LIST (region);
CREATE TABLE events_2026_03_emea PARTITION OF events_2026_03
FOR VALUES IN ('EU', 'UK', 'MEA');
The cost shows up as object count: three months times four regions is twelve partitions, and a year of them is forty-eight objects to create, index, and analyse. Automation is not optional at that scale â generate the DDL from a calendar table in a scheduled job, and validate afterwards that a default partition exists everywhere, because a missing default is the classic cause of midnight insert failures.
How pruning actually happens
Pruning is a planning-time decision, and you can watch it happen. The optimiser takes the predicate, intersects it with the partition bounds, and excludes anything disjoint. If the predicate cannot be expressed against the bound â a function on the key, a cast, an inequality on a non-key column â the intersection is undefined and every partition survives.
-- Predicate on the partition key: pruned to a single partition
EXPLAIN (ANALYZE, BUFFERS)
SELECT count(*), sum(amount)
FROM orders
WHERE order_date >= DATE '2026-02-01'
AND order_date < DATE '2026-02-02';
-- Wrapped key defeats pruning: every partition is scanned
EXPLAIN (ANALYZE, BUFFERS)
SELECT count(*)
FROM orders
WHERE to_char(order_date, 'YYYY-MM') = '2026-02';
-- The same question, expressed so the bound applies
EXPLAIN (ANALYZE, BUFFERS)
SELECT count(*)
FROM orders
WHERE order_date >= DATE '2026-02-01'
AND order_date < DATE '2026-03-01';
Read the plan for two signals. A pruned plan lists one or two child relations under the append node and shows a correspondingly low read count; an unplanned scan lists every partition with rows estimates near the table total. The lesson generalises beyond partitioning: any expression wrapping a key column in the predicate costs you pruning, which is the same reason it costs you index usage.
Maintenance: adds, merges, splits, and exchanges
A partitioned table that is never maintained degrades in two directions: old partitions accumulate and bloat statistics, while future partitions are missing and inserts fail. Both are solved with scheduled maintenance rather than heroics.
-- Add next month ahead of time so inserts never fail
ALTER TABLE orders ADD PARTITION IF NOT EXISTS
FOR VALUES FROM ('2026-04-01') TO ('2026-05-01');
-- Attach a pre-loaded staging table as a partition: metadata-only swap
ALTER TABLE orders DETACH PARTITION orders_2026_03_staging;
-- ... load and index the staging table offline ...
ALTER TABLE orders ATTACH PARTITION orders_2026_03
FOR VALUES FROM ('2026-03-01') TO ('2026-04-01');
-- Retire old data in one statement rather than a long-running delete
DROP TABLE orders_2024_01;
-- Merge adjacent small partitions to reduce object count
ALTER TABLE orders MERGE PARTITIONS
FOR VALUES FROM ('2025-11-01') TO ('2025-12-01'),
FOR VALUES FROM ('2025-12-01') TO ('2026-01-01')
INTO PARTITION orders_2025_q4_tail;
Attach and detach deserve special attention because they change the game for loading. A bulk load into a staging table, built and indexed offline, becomes a partition of the main table in a metadata operation that takes milliseconds â no long insert lock, no index build on the live table. That pattern is how warehouses load a day of data without blocking the queries that read last month.
Retention then becomes a DROP rather than a DELETE, which is the operational payoff that makes partitioning worth its complexity: dropping a partition is near-instantaneous regardless of row count, while deleting the same rows would rewrite every page.
Choosing the key from the query, not the table
Before declaring a partition key, write down the three most frequent queries and check which columns they constrain. If they all filter by date, range on date. If they filter by tenant and date, consider range on date with list or hash on tenant as the second level, or vice versa if tenant boundaries drive retention. If the dominant access is point lookup on a high-cardinality identifier, partitioning will not help and you want an index.
Watch for keys that fight your workload. A status column with three values partitions a table into three equally sized slabs that every query touches â useless. A timestamp with second precision on a small table creates thousands of partitions, each too small to amortise the planning overhead. Rule of thumb: aim for partitions that hold at least a few hundred megabytes after indexes, and no more than a few hundred partitions in total.
The costs nobody budgets for
Every partition adds a planning decision, an index, statistics, and a file descriptor. Beyond a few hundred objects, parse and plan time becomes measurable on short queries, and background maintenance â autovacuum, statistics collection, index rebuilds â multiplies across all of them. This is why aggressive subpartitioning should be justified by a measured predicate, not by symmetry.
Cross-partition operations are the second cost. A query grouping by the partition key can be optimised to skip row-by-row evaluation in some engines; a query joining two partitioned tables on different keys requires pruning on both sides to compound. And a global uniqueness constraint â primary key including the partition key, or a unique index that excludes it â may be unrepresentable, which forces application-level guarantees you must then test.
đĄProve pruning before you ship
Run the three most frequent queries with EXPLAIN ANALYZE immediately after partitioning. If the plan still lists every child relation, fix the predicate shape or the key choice now, while the change is cheap.
Common Mistakes
Partitioning on a low-cardinality column such as status
Fix: Choose a key that matches the dominant predicates and yields partitions of useful size
Wrapping the key in a function inside the predicate and silently losing pruning
Fix: Express the predicate as a range against the key, or index the expression if the form is unavoidable
No default or future partition, so inserts fail outside the declared range
Fix: Schedule pre-creation of future partitions and keep a default catch-all where the engine allows it
Deleting old rows instead of dropping partitions
Fix: Use detach, archive, and drop so retention is a metadata operation rather than a rewrite
Best Practices
- Derive the key from the three most frequent queries, not from convention
- Automate partition creation and validate that a default exists everywhere
- Load through attach of pre-built staging tables to avoid locking the live table
- Keep total partition counts in the low hundreds and sizes comfortably above a few hundred megabytes
- Re-run EXPLAIN ANALYZE on the hot path after any change to the scheme
Interview Questions
Q1: How does partition pruning work?
At planning time the optimiser intersects the predicate with declared partition bounds and excludes disjoint partitions from the plan.
Q2: When does pruning silently fail?
When the key is wrapped in a function or cast, when the predicate targets a non-key column, or when the range has no bound the engine can evaluate.
Q3: Range versus list partitioning?
Range suits ordered values such as dates and answers interval predicates; list suits a finite known set and answers equality.
Q4: Why is attach preferable to inserting a bulk load?
Attaching a pre-loaded, pre-indexed table is a metadata operation, so it avoids locking and index build time on the live table.
Key Takeaways
- Partitioning pays off only when the key matches the dominant predicates
- Pruning happens at planning time and is lost the moment the key is wrapped in a function
- Composite schemes solve two-dimensional access but multiply object counts
- Maintenance should be scheduled: pre-create, attach, and drop rather than insert and delete
- Budget for planning overhead: hundreds of small partitions cost more than they save