Sub topic 14
Partitionwise joins and aggregates
This chapter covers two planner features that work on top of partition pruning. They let PostgreSQL join and aggregate partitioned tables one partition at a time. It assumes you can read basic EXPLAIN output and that you know how PARTITION BY works for range, list and hash tables.
What "partitionwise" means
Without these features, PostgreSQL treats a partitioned table as one combined input. A join of two partitioned tables first appends all partitions of each side and then joins the two large results. An aggregate appends all rows and then groups them.
With partitionwise planning, the planner works on smaller pieces:
- A partitionwise join joins each partition of one table to the matching partition of the other table. The planner then appends the results.
- A partitionwise aggregate groups or aggregates inside each partition. The planner then appends the results, and it combines them first if it has to.
Smaller pieces help in three ways. Each hash table or sort is smaller, so it is more likely to fit in work_mem. Each piece can use the index and join method that suits its own statistics. The pieces can also run in parallel workers.
Both features are off by default.
| Setting | Default | Effect when on |
|---|---|---|
| `enable_partitionwise_join` | `off` | Lets the planner join matching partitions pairwise |
| `enable_partitionwise_aggregate` | `off` | Lets the planner aggregate each partition separately |
Setting up two compatible tables
A partitionwise join needs two tables partitioned the same way. This example hash-partitions orders and shipments on customer_id, with the same modulus on both.
CREATE TABLE orders (
order_id bigint NOT NULL,
customer_id bigint NOT NULL,
placed_at date NOT NULL,
total numeric,
PRIMARY KEY (order_id, customer_id)
) PARTITION BY HASH (customer_id);
CREATE TABLE orders_p0 PARTITION OF orders FOR VALUES WITH (MODULUS 2, REMAINDER 0);
CREATE TABLE orders_p1 PARTITION OF orders FOR VALUES WITH (MODULUS 2, REMAINDER 1);
CREATE TABLE shipments (
shipment_id bigint NOT NULL,
order_id bigint NOT NULL,
customer_id bigint NOT NULL,
shipped_at date,
PRIMARY KEY (shipment_id, customer_id)
) PARTITION BY HASH (customer_id);
CREATE TABLE shipments_p0 PARTITION OF shipments FOR VALUES WITH (MODULUS 2, REMAINDER 0);
CREATE TABLE shipments_p1 PARTITION OF shipments FOR VALUES WITH (MODULUS 2, REMAINDER 1);
INSERT INTO orders
SELECT g, g % 1000, DATE '2026-01-01' + (g % 90), (g % 50) + 1.5
FROM generate_series(1, 100000) AS g;
INSERT INTO shipments
SELECT g, g, g % 1000, DATE '2026-01-03' + (g % 90)
FROM generate_series(1, 100000) AS g;
ANALYZE orders;
ANALYZE shipments;Because both tables use hash partitioning on customer_id with modulus 2, a customer's rows land in partition p0 of both tables or in p1 of both. An order in orders_p0 can only match shipments in shipments_p0. That fact is what lets the planner skip the cross-partition comparisons.
Reading a partitionwise join plan
First look at the plan with the feature off.
SET enable_partitionwise_join = off;
EXPLAIN (COSTS OFF)
SELECT o.customer_id, count(*)
FROM orders o
JOIN shipments s
ON s.customer_id = o.customer_id
AND s.order_id = o.order_id
GROUP BY o.customer_id;The join node sits above two Append nodes. All of orders is combined and all of shipments is combined, and then one join runs over the two combined inputs. Now turn the feature on.
SET enable_partitionwise_join = on;
EXPLAIN (COSTS OFF)
SELECT o.customer_id, count(*)
FROM orders o
JOIN shipments s
ON s.customer_id = o.customer_id
AND s.order_id = o.order_id
GROUP BY o.customer_id;The exact plan depends on your version and statistics. The shape to look for is this:
HashAggregate
Group Key: o.customer_id
-> Append
-> Hash Join
Hash Cond: ((s_1.customer_id = o_1.customer_id) AND (s_1.order_id = o_1.order_id))
-> Seq Scan on shipments_p0 s_1
-> Hash
-> Seq Scan on orders_p0 o_1
-> Hash Join
Hash Cond: ((s_2.customer_id = o_2.customer_id) AND (s_2.order_id = o_2.order_id))
-> Seq Scan on shipments_p1 s_2
-> Hash
-> Seq Scan on orders_p1 o_2The Append is now above the joins. Each Hash Join pairs orders_p0 with shipments_p0, or orders_p1 with shipments_p1. No join pairs p0 with p1.
When the planner can use a partitionwise join
The planner uses a partitionwise join only when it can prove that matching rows are always in matching partitions. These conditions must hold:
- Both tables are partitioned, and the partition keys have the same data types.
- The partition methods and bounds line up. Before PostgreSQL 13 the bounds had to be identical. From PostgreSQL 13, tables whose bounds differ can still qualify when each partition on one side matches at most one partition on the other.
- The join condition includes an equality between every partition key column of one table and the corresponding column of the other. Joining on
order_idalone, which is not the partition key, does not qualify. - Both settings and plan costs allow it. The planner picks the partitionwise plan only when it estimates it to be cheaper.
A join between a partitioned table and an ordinary table is not a partitionwise join. A join whose condition uses only part of a multi-column partition key does not qualify either.
If the plan keeps the two Append nodes under the join, check the join condition and the partition definitions first. Missing the partition key in the ON clause is the most common cause.
Partitionwise aggregates
Aggregation has two modes, and which one the planner uses depends on the GROUP BY clause.
Full partitionwise aggregation happens when the GROUP BY includes all partition key columns. Every group lives in exactly one partition, so each partition can finish its own groups and the planner only appends the results.
SET enable_partitionwise_aggregate = on;
EXPLAIN (COSTS OFF)
SELECT customer_id, sum(total)
FROM orders
GROUP BY customer_id;Expect an Append over one HashAggregate (or GroupAggregate) per partition, and no aggregate above the Append.
Partial partitionwise aggregation happens when the GROUP BY does not include the partition key. A group such as one placed_at date can have rows in several partitions. Each partition computes a partial result, and a final step combines them.
EXPLAIN (COSTS OFF)
SELECT placed_at, sum(total)
FROM orders
GROUP BY placed_at;Expect a Finalize HashAggregate above an Append of Partial HashAggregate nodes. This still reduces work, because each partition shrinks its rows to a few partial results before they are combined. It saves less than full aggregation, since the final step still has to merge groups from every partition.
Combining with pruning and parallelism
Partitionwise planning works together with partition pruning. The planner prunes partitions that the WHERE clause excludes, and then plans the join or aggregate over the partitions that remain. A filter on the partition key therefore reduces the number of per-partition plans, which also limits the planning cost described earlier.
Each per-partition join or aggregate can also run in a parallel worker. With many partitions, a partitionwise plan gives the parallel query machinery several independent units of work. Whether the planner chooses parallelism still depends on the usual settings, such as max_parallel_workers_per_gather, and on table size.
Practical guidance
- Enable the settings narrowly.
SET LOCAL enable_partitionwise_join = on;inside a transaction, orALTER ROLE reporting SET enable_partitionwise_aggregate = on;, keeps the extra planning cost away from your short queries. - Design related tables with matching partition keys, methods and bounds. If
ordersandshipmentsare both partitioned by month on a date column, a join on that column and the order key can be partitionwise. - Keep the partition count moderate. Planning memory and time grow with the number of partitions, and this feature multiplies that cost.
- Compare plans with
EXPLAIN (ANALYZE)before and after. The planner picks partitionwise plans by cost estimate, so stale statistics can lead to a worse choice. RunANALYZEon the parent table after bulk loads. - Check the result when you use a join or group on a column that is not the partition key. The query will still be correct, but you should not expect the join to become partitionwise.
Exercise
A table sales is range partitioned by sale_date. You run SELECT region, sum(amount) FROM sales GROUP BY region with enable_partitionwise_aggregate = on. Is the aggregation full or partial, and what node do you expect above the Append?
Show answer
It is partial. region is not the partition key, so one region can have rows in many partitions. Each partition computes a Partial aggregate, and a Finalize aggregate node above the Append combines the partial results. Grouping by sale_date (or including it in the GROUP BY) would allow full partitionwise aggregation with no node above the Append.
Exercise
You join orders and shipments, both hash partitioned on customer_id with the same modulus. With enable_partitionwise_join = on, the plan still shows two Append nodes under a single join. The query joins them with ON s.order_id = o.order_id. What is wrong, and how do you fix it?
Show answer
The join condition does not include an equality on the partition key customer_id, so the planner cannot show that matching rows are in matching partitions. Add AND s.customer_id = o.customer_id to the ON clause. Then check with EXPLAIN that the Append appears above the per-partition joins.