Sub topic 3
Planning the Partition Lifecycle
This chapter assumes you can create range-partitioned tables, you know primary keys and indexes, and you run PostgreSQL 14 or later. The examples use the orders table from earlier chapters.
Lifecycle stages
A time-based partition moves through four stages: creation, attachment, active use, and removal. Plan all four before the first partition goes live.
Attaching and detaching partitions
Create the partition ahead of time and add a matching CHECK constraint. PostgreSQL can then skip a full scan during ATTACH PARTITION.
CREATE TABLE orders_2026_03 (LIKE orders INCLUDING DEFAULTS);
ALTER TABLE orders_2026_03
ADD CONSTRAINT orders_2026_03_bounds
CHECK (order_date >= DATE '2026-03-01'
AND order_date < DATE '2026-04-01');
ALTER TABLE orders
ATTACH PARTITION orders_2026_03
FOR VALUES FROM ('2026-03-01') TO ('2026-04-01');
ALTER TABLE orders
DETACH PARTITION orders_2026_03 CONCURRENTLY;::: callout warning DETACH PARTITION ... CONCURRENTLY cannot run inside a transaction block, and it fails when the partitioned table has a default partition. :::
Migrating an existing table
Build the partitioned table under a new name, copy rows in date batches, check the row counts, and then swap the names during a short window when writes are paused.
BEGIN;
ALTER TABLE orders RENAME TO orders_old;
ALTER TABLE orders_new RENAME TO orders;
COMMIT;Retention and maintenance
Dropping an old partition removes its rows at once. A DELETE of the same rows leaves dead tuples that vacuum must clean. Run detach, archive, and drop as a scheduled job.
Testing and inspecting partitions
Confirm pruning with EXPLAIN, and confirm where rows land with tableoid.
EXPLAIN (COSTS OFF)
SELECT count(*) FROM orders
WHERE order_date >= DATE '2026-03-10'
AND order_date < DATE '2026-03-15';
SELECT tableoid::regclass AS partition, count(*)
FROM orders
GROUP BY tableoid;Limitations and operational risks
- Primary and unique keys must include the partition key.
- Changing a row's partition key moves the row to another partition, which is a delete followed by an insert.
- A default partition holding rows that match a new partition's bounds blocks that
ATTACH PARTITION. - Thousands of partitions increase planning time.
Exercise
Why add the CHECK constraint before running ATTACH PARTITION?
Show answer
The matching CHECK constraint proves the rows satisfy the bounds, so PostgreSQL skips the full-table scan it would otherwise run while holding a strong lock.