Sub topic 13
Multilevel partitioning
This chapter assumes you can create range, list and hash partitioned tables, and that you know how partition pruning and partitioned indexes work. It covers partitions that are themselves partitioned, which PostgreSQL calls multilevel or sub-partitioning. It explains when a second level is worth the cost, how rows are routed through the levels, and which gotchas to expect.
What multilevel partitioning is
A partition can be declared with its own PARTITION BY clause. That partition then becomes a partitioned table too. It stores no rows itself and passes them down to its own partitions. Only the bottom partitions, called leaf partitions, hold data.
Each level can use a different method and a different key. A common layout is range on a time column at the top and hash or list on a second column below it.
CREATE TABLE events (
event_id bigint NOT NULL,
tenant_id int NOT NULL,
created_at timestamptz NOT NULL
) PARTITION BY RANGE (created_at);
CREATE TABLE events_2026_01 PARTITION OF events
FOR VALUES FROM ('2026-01-01') TO ('2026-02-01')
PARTITION BY HASH (tenant_id);
CREATE TABLE events_2026_01_h0 PARTITION OF events_2026_01 FOR VALUES WITH (MODULUS 2, REMAINDER 0);
CREATE TABLE events_2026_01_h1 PARTITION OF events_2026_01 FOR VALUES WITH (MODULUS 2, REMAINDER 1);In this example events is partitioned by range. events_2026_01 is both a partition of events and a hash partitioned table. events_2026_01_h0 and events_2026_01_h1 are leaves.
How rows are routed
When you insert into the top table, PostgreSQL evaluates the top-level key to pick a child. If that child is itself partitioned, PostgreSQL evaluates the child's key to pick the next one. It repeats this until it reaches a leaf.
For a row with created_at = '2026-01-15' and tenant_id = 7, the range level selects events_2026_01. The hash level then selects events_2026_01_h0 or events_2026_01_h1, depending on the hash of 7.
You can see the final location with tableoid::regclass, which reports leaf partitions:
INSERT INTO events (event_id, tenant_id, created_at)
VALUES (1, 7, '2026-01-15 10:00+00'),
(2, 8, '2026-01-16 11:00+00');
SELECT tableoid::regclass AS leaf, event_id, tenant_id
FROM events
ORDER BY event_id;The leaf column shows one of the two hash leaves for each row. Which leaf gets which row depends on PostgreSQL's internal hash function. Don't hard-code that assignment in application logic.
If no partition at some level accepts the row, the insert fails with an error such as no partition of relation "events" found for row. A row for February fails here because only the January partition exists. A default partition at any level catches rows that fit nothing else at that level.
Choosing the combination
Pick a second level only when it solves a problem the first level does not. These are the usual pairings.
| Top level | Second level | Typical reason |
|---|---|---|
| Range on time | Hash on an id | One month is still too large for one table, and you want smaller tables and indexes without changing the retention unit |
| Range on time | List on a category | Queries almost always filter by both time and a small set of categories, such as region |
| List on tenant group | Range on time | A few very large tenants need their own time-based retention |
| Hash | Range | Rare. Usually a sign that the design needs rethinking |
The top level should usually match the data lifecycle. If you drop data by month, make month the top level. Then retention is still one DETACH PARTITION of a whole subtree, not one operation per leaf.
Pruning across levels
Pruning is applied level by level. A filter on the top key removes whole subtrees. A filter on the second key then removes leaves inside the subtrees that remain.
EXPLAIN
SELECT *
FROM events
WHERE created_at >= '2026-01-10' AND created_at < '2026-01-20'
AND tenant_id = 7;With this query the planner discards every month except January. Inside January it keeps only the hash leaf that can contain tenant_id = 7. The plan should list one leaf scan.
Dropping the tenant_id filter keeps both January leaves. Dropping the created_at filter keeps a hash leaf under every month, because every month's hash level can hold tenant 7. The number of scans is then the number of months, not one.
This is the cost of multilevel designs. A query that filters on only one of the keys still touches many leaves, and the plan can grow long. A hash second level only helps queries that give an equality condition on its key.
Keys and indexes in a hierarchy
The rule from the earlier chapter applies at every level. A primary key or unique constraint must include the partition key columns of every level above it, and of the level itself. For events, a primary key needs both created_at and tenant_id:
CREATE TABLE events_pk (
event_id bigint NOT NULL,
tenant_id int NOT NULL,
created_at timestamptz NOT NULL,
PRIMARY KEY (event_id, tenant_id, created_at)
) PARTITION BY RANGE (created_at);The primary key is accepted, but it only guarantees uniqueness of the full combination. It does not make event_id unique by itself. Within each leaf the constraint is enforced by a local index, and the partition keys make cross-leaf duplicates of the whole key impossible.
Indexes created on the top table cascade through every level to every leaf, including leaves added later:
CREATE INDEX ON events (tenant_id, created_at);Each leaf gets its own physical index. With many leaves this creates many index relations, and each one costs planning time and catalog space.
Attaching and detaching subtrees
A sub-partitioned partition can be detached and attached like any other partition. Detaching events_2026_01 removes the whole subtree from events in one metadata operation. The leaves stay attached to events_2026_01, so you can archive or drop them together.
ALTER TABLE events DETACH PARTITION events_2026_01 CONCURRENTLY;
DROP TABLE events_2026_01;Dropping a partitioned table drops its leaves as well. You can also build a new month ahead of time as a standalone partitioned table, create its leaves, load data, and attach it last:
CREATE TABLE events_2026_02 (LIKE events INCLUDING DEFAULTS INCLUDING CONSTRAINTS)
PARTITION BY HASH (tenant_id);
CREATE TABLE events_2026_02_h0 PARTITION OF events_2026_02 FOR VALUES WITH (MODULUS 2, REMAINDER 0);
CREATE TABLE events_2026_02_h1 PARTITION OF events_2026_02 FOR VALUES WITH (MODULUS 2, REMAINDER 1);
ALTER TABLE events ATTACH PARTITION events_2026_02
FOR VALUES FROM ('2026-02-01') TO ('2026-03-01');Attaching checks that existing rows satisfy the new range. For a partitioned table, PostgreSQL can't always skip that scan the way it can for a plain table with a matching CHECK constraint, so test attach time on realistic data first. Load the data after the attach if the check cost is a problem. The range constraint is then enforced by routing.
Costs and failure modes
Leaf count multiplies across levels. Twelve months with 16 hash leaves each gives 192 leaves, and a year of retention with daily top-level partitions and 32 hash leaves gives more than 11,000. Consider these effects:
- Planning time. The planner works over all partitions that survive pruning. Queries that cannot be pruned on both keys grow slower as the leaf count rises.
- Memory. Each partition's metadata is cached per session. Many leaves increase memory use for long-lived connections.
- Locks. A query that touches many leaves takes a lock on each one. Large counts can exhaust
max_locks_per_transaction. - Maintenance. Each leaf needs its own vacuum and analyze.
ANALYZEon the top table gathers statistics for the partitioned tables themselves, but autovacuum does not do this automatically for partitioned parents, so schedule it. - Small tables. Leaves with only a few thousand rows give no benefit and cost overhead.
A second level is easy to add and hard to remove. Changing the structure means creating a new table and moving the data. Start with one level, measure, and add a second only when a query pattern or table size demands it.
Checking the structure
The built-in function pg_partition_tree lists every partition under a table with its parent, whether it is a leaf and its depth:
SELECT relid, parentrelid, isleaf, level
FROM pg_partition_tree('events');Rows with isleaf = false are partitioned tables that hold no data. The level column is 0 for events itself, 1 for events_2026_01, and 2 for the hash leaves. Use pg_partition_tree to confirm that a new month is built as intended before you attach it, and to count leaves when you review the design.
Exercise
A table is partitioned by RANGE on createdat, and each month is sub-partitioned by HASH on tenantid into 4 leaves. A query filters on tenantid = 42 only, with no condition on createdat, and the table holds 24 months. How many leaves does the plan scan, and what change would reduce that number?
Show answer
It scans 24 leaves, one hash leaf per month, because the tenant filter prunes the hash level in every month but nothing prunes the range level. Adding a createdat condition that covers fewer months reduces the count. If such queries are common and cannot include a time filter, the second level is not helping, and a design that uses tenantid as the top-level key or a plain single-level range table is worth testing.
Exercise
You need to remove January 2026 data from a two-level events table in one step, without running a bulk DELETE. Which statements do you run, and why do you not need to touch the hash leaves one by one?
Show answer
Run ALTER TABLE events DETACH PARTITION events202601 CONCURRENTLY; then DROP TABLE events202601;. The detach removes the whole January subtree in one operation because the hash leaves belong to events202601, not directly to events. Dropping events202601 then drops its leaves with it.