Sub topic 12
Partition hierarchies and subpartitioning
Assume you know basic PostgreSQL CREATE TABLE syntax, partition bounds, indexes, and query plans. This chapter shows how one partitioned table can contain other partitioned tables.
What a partition hierarchy is
A partition hierarchy is a tree of tables. The root is the logical table that applications query. Its direct children divide rows using the first partition key. A child can either store rows itself or act as another partitioned parent.
Subpartitioning applies a second partitioning rule inside each first-level partition. For example, you can divide orders by month and then distribute each month by customer hash.
CREATE TABLE orders (
order_id bigint NOT NULL,
customer_id bigint NOT NULL,
order_date date NOT NULL,
amount numeric(12, 2) NOT NULL
) PARTITION BY RANGE (order_date);
CREATE TABLE orders_2026_01
PARTITION OF orders
FOR VALUES FROM ('2026-01-01') TO ('2026-02-01')
PARTITION BY HASH (customer_id);
CREATE TABLE orders_2026_01_0
PARTITION OF orders_2026_01
FOR VALUES WITH (MODULUS 2, REMAINDER 0);
CREATE TABLE orders_2026_01_1
PARTITION OF orders_2026_01
FOR VALUES WITH (MODULUS 2, REMAINDER 1);
INSERT INTO orders (order_id, customer_id, order_date, amount)
VALUES (1, 42, DATE '2026-01-15', 19.99);The insert first matches orders_2026_01 because of order_date. PostgreSQL then hashes customer_id and sends the row to either orders_2026_01_0 or orders_2026_01_1.
Inspecting the hierarchy
Use pg_partition_tree to inspect the hierarchy and identify each table's level.
SELECT
relid::regclass AS table_name,
parentrelid::regclass AS parent_table,
isleaf,
level
FROM pg_partition_tree('orders'::regclass)
ORDER BY level, table_name;A partitioned parent has isleaf = false. It is a routing layer and does not hold rows directly. A leaf partition has isleaf = true and stores rows.
Design trade-offs
Subpartitioning can reduce the amount of data scanned and let you manage data at two useful boundaries. It also increases the number of relations, indexes, maintenance tasks, and planning work. Every first-level partition needs a complete second-level layout. A missing partition at any level causes an insert to fail unless a suitable default partition exists.
Use a second level only when it supports a real query or maintenance need. Do not add layers merely to make the hierarchy look organized.
Exercise
In the example, which partition receives an order dated 2026-01-15, and what determines its final leaf?
Show answer
PostgreSQL first selects orders202601 using orderdate. It then hashes customerid and uses the resulting remainder to select orders2026010 or orders2026011.