Sub topic 15
Limitations and common pitfalls
Partitioning is a physical design choice with real costs. This chapter covers the limits PostgreSQL enforces and the mistakes that make partitioned tables slower or harder to operate than the plain tables they replaced. It assumes you can read basic EXPLAIN output, know how primary keys and unique constraints work, and have followed the earlier chapters on PARTITION BY, pruning, indexes, and ATTACH/DETACH. The examples reuse the measurements table from those chapters.
Too many partitions
More partitions do not mean faster queries. Each partition is a separate table with its own files, catalog entries, and indexes. This has three costs.
- Planning time. The planner must consider every partition that survives pruning. A query that touches thousands of partitions can spend more time planning than executing.
- Memory. Each partition the planner or executor opens adds to the backend's memory use.
- Locks. A query takes a lock on every partition it touches, plus each partition's indexes. A query that cannot prune can exhaust
max_locks_per_transaction, which fails with "out of shared memory".
A practical range is tens to a few hundred partitions. Thousands need testing. Choose the partition granularity so each partition is large enough to matter. Daily partitions for a table that gets 10,000 rows a day add overhead and give nothing back. Monthly partitions are usually enough.
Rows with no matching partition
A row whose key fits no partition makes the insert fail:
INSERT INTO measurements (device_id, recorded_at, reading)
VALUES (1, '2027-01-15', 20.5);
-- ERROR: no partition of relation "measurements" found for row
-- DETAIL: Partition key of the failing row contains (recorded_at) = (2027-01-15 00:00:00+00).This is a common production outage. Nobody created next month's partition, and the application starts failing at midnight. Two defenses work together.
- Automate partition creation ahead of time, with a scheduled job or an extension such as
pg_partman. Create at least one or two future partitions. - Optionally add a default partition so inserts never fail.
A default partition has its own costs.
- It hides the problem. Rows pile up in
measurements_defaultand nobody notices. - Adding a partition requires proving that the default holds no rows in the new range. PostgreSQL scans the default partition while holding a strong lock on it. A large default partition makes that slow.
- Rows that fit the new range and already sit in the default partition block the new partition. You must move them out first.
A CHECK constraint on the default partition that excludes the new range lets PostgreSQL skip the scan:
ALTER TABLE measurements_default ADD CONSTRAINT measurements_default_no_apr
CHECK (NOT (recorded_at >= '2026-04-01' AND recorded_at < '2026-05-01'));Monitor the default partition with SELECT count(*) FROM ONLY measurements_default. Treat any nonzero count as a bug to investigate.
Bounds are half-open
Range bounds include the lower value and exclude the upper one. A frequent mistake is writing TO ('2026-01-31') for a January partition. Rows from January 31 then have no home. Use the first instant of the next period as the upper bound, so adjacent partitions share a boundary value and leave no gap. Overlapping ranges are rejected when you create the partition. Gaps are not rejected, so you must watch for them yourself.
Pruning that silently does not happen
Partition pruning only works when the planner can compare the filter to the partition bounds. These filters defeat it:
- no condition on the partition key at all
- an expression wrapped around the key column
- a cast that changes the key's type
-- Scans every partition: the key is hidden inside a function call
EXPLAIN SELECT count(*) FROM measurements
WHERE date_trunc('month', recorded_at) = '2026-02-01';
-- Scans only measurements_2026_02: the key is compared directly to constants
EXPLAIN SELECT count(*) FROM measurements
WHERE recorded_at >= '2026-02-01' AND recorded_at < '2026-03-01';Rewrite the condition as a range on the bare column. Comparing against a stable expression such as now() still prunes. PostgreSQL does this at executor startup, and the plan shows Subplans Removed: N instead of omitting the partitions. Values passed as parameters in prepared statements prune the same way.
The diagram gives a quick checklist when a query touches more partitions than expected.
Unique constraints are per partition
PostgreSQL has no global indexes. Each partition has its own index, so a unique index can only guarantee uniqueness if the partition key is part of it. That is why a primary key or unique constraint must include every partition key column. A table partitioned by placed_at cannot enforce that order_id alone is unique across all partitions. Your options are:
- Accept
(order_id, placed_at)as the key. - Use a globally unique generator, such as a sequence or UUID, so collisions cannot occur in practice.
- Enforce uniqueness in the application, which is weaker and race-prone.
Related restrictions:
- Exclusion constraints are not supported on partitioned tables.
- A foreign key that references a partitioned table must reference its full unique key, including the partition key columns. Foreign keys from a partitioned table to another table work in PostgreSQL 11 and later. Foreign keys to a partitioned table need PostgreSQL 12 or later.
Indexes: no concurrent build on the parent
CREATE INDEX CONCURRENTLY is not supported on a partitioned table. A plain CREATE INDEX on the parent locks writes on every partition while it builds. For a large live table, build the indexes one partition at a time:
-- 1. Create an invalid placeholder index on the parent only
CREATE INDEX measurements_device_idx ON ONLY measurements (device_id);
-- 2. Build each partition's index without blocking writes
CREATE INDEX CONCURRENTLY measurements_2026_01_device_idx
ON measurements_2026_01 (device_id);
-- 3. Attach it to the parent index
ALTER INDEX measurements_device_idx
ATTACH PARTITION measurements_2026_01_device_idx;Repeat steps 2 and 3 for every partition. The parent index becomes valid once all partitions are attached. Partitions created later get a matching index automatically.
Detach, attach, and default partition interactions
DETACH PARTITION ... CONCURRENTLYcannot run inside a transaction block. It also fails if the table has a default partition.- If a concurrent detach is cancelled or the session dies, the partition is left in a "detach pending" state. Finish it with:
ALTER TABLE measurements DETACH PARTITION measurements_2026_01 FINALIZE;ATTACH PARTITIONscans the new table to verify its rows fit the bounds, unless a matchingCHECKconstraint already proves it. Skipping the constraint on a large table means a long scan under a lock.- A partition must have exactly the parent's columns, in name and type. It cannot add its own extra columns.
Row movement and the partition key
An UPDATE that changes the partition key moves the row to another partition. PostgreSQL performs it as a delete from one partition and an insert into the other. This works, but it is more expensive than an in-place update. Under concurrency, a transaction that updates a row another transaction has just moved can fail with "tuple to be locked was already moved to another partition due to concurrent update". Choose a key that does not change after the row is created. A creation timestamp is a good key. A status column is not.
Statistics on the parent
Autovacuum vacuums and analyzes the partitions, but it never analyzes the partitioned parent table itself. Planner statistics for the parent, which affect some join and aggregate estimates, stay empty or stale. Run ANALYZE measurements; manually after large loads, and after attaching or detaching partitions.
Partitionwise operations are off by default
Joining two tables partitioned on the same key, or aggregating by the partition key, can run partition by partition. That reduces memory use and allows more parallelism. The planner settings enable_partitionwise_join and enable_partitionwise_aggregate default to off because planning cost grows with partition count. Turn them on for specific workloads where the partition schemes match, and compare plans with and without.
Other limits to remember
- You cannot convert an existing table into a partitioned table with
ALTER TABLE. Create a new partitioned table and load or attach the old data. - You cannot change the partition key or method after creation. Changing it means rebuilding the table.
- Hash partitions cannot be resized in place. Going from 4 to 8 partitions means creating a new set and moving the data.
- Queries without a filter on the partition key scan every partition. Several small scans can cost more than one scan of a single table.
Summary of pitfalls
| Pitfall | Symptom | Fix |
|---|---|---|
| Missing future partition | Insert error "no partition ... found for row" | Create partitions ahead of time; consider a default partition |
| Unmonitored default partition | Rows accumulate; attaching new partitions gets slow | Alert on its row count; add a `CHECK` constraint before attaching |
| Wrong bound | Gaps at period ends | Use the next period's first instant as the upper bound |
| Function or cast on the key | `EXPLAIN` lists every partition | Filter on the bare key column with a range |
| Key-only uniqueness | Error creating primary key | Include the partition key in the constraint |
| Index build on large live table | Writes blocked | `ON ONLY` parent, then `CONCURRENTLY` per partition |
| Stale parent statistics | Poor join estimates | Run `ANALYZE` on the parent |
| Too many partitions | Slow planning, lock errors | Use coarser partitions; raise `max_locks_per_transaction` only if needed |
Exercise
A table orders is partitioned by RANGE on placed_at. A developer runs SELECT * FROM orders WHERE placed_at::date = '2026-02-10' and EXPLAIN shows every partition scanned. Why, and how do you fix the query?
Show answer
The cast placed_at::date wraps the partition key, so the planner cannot compare it to the partition bounds and cannot prune. Rewrite it as a range on the bare column: WHERE placed_at >= '2026-02-10' AND placed_at < '2026-02-11'. If placed_at is a date column, no cast is needed.
Exercise
You need to add an index on a 2 TB partitioned table that takes live writes. Why is plain CREATE INDEX on the parent risky, and what steps avoid the problem?
Show answer
A plain CREATE INDEX on the parent builds on every partition and blocks writes while it does, and CREATE INDEX CONCURRENTLY is not allowed on the parent. Run CREATE INDEX ... ON ONLY parent (...) to create an invalid parent index. Then run CREATE INDEX CONCURRENTLY on each partition. Finally run ALTER INDEX parent_index ATTACH PARTITION partition_index for each one. The parent index becomes valid after the last attach.
Exercise
Your team wants order_id alone to be unique on a table partitioned by placed_at. Can PostgreSQL enforce this with a primary key? Name two alternatives.
Show answer
No. A primary key or unique constraint on a partitioned table must include all partition key columns, because uniqueness is enforced per partition by local indexes. Alternatives: use (order_id, placed_at) as the key and generate order_id from a sequence or UUID so it is unique in practice, or enforce uniqueness in the application layer (weaker, and race-prone).