Sub topic 11
Attaching and detaching partitions
This chapter assumes you can create a range-partitioned table, know what the partition constraint is, and have read basic EXPLAIN output. It builds on the measurements table from the range partitioning chapter.
Why attach and detach exist
CREATE TABLE ... PARTITION OF creates a new, empty partition. ATTACH PARTITION and DETACH PARTITION are the other two ways to change a partition set, and they are what you use on a live system:
- Attach turns an existing table into a partition. You can load and check the data offline, then publish it with a short metadata operation.
- Detach turns a partition back into an ordinary table. The data stays intact. You can then archive it, move it, or drop it.
Both are cheap compared with INSERT ... SELECT or a bulk DELETE, because no rows are copied or rewritten. The cost to watch is the locks and the validation scan, covered below.
Attaching a partition
The standard pattern is to build the new partition as a standalone table, load it, and then attach it.
CREATE TABLE measurements (
device_id int NOT NULL,
recorded_at timestamptz NOT NULL,
reading numeric
) PARTITION BY RANGE (recorded_at);
CREATE TABLE measurements_2026_01 PARTITION OF measurements
FOR VALUES FROM ('2026-01-01') TO ('2026-02-01');
CREATE TABLE measurements_2026_02 PARTITION OF measurements
FOR VALUES FROM ('2026-02-01') TO ('2026-03-01');
CREATE TABLE measurements_2026_03 (LIKE measurements INCLUDING DEFAULTS INCLUDING CONSTRAINTS);
INSERT INTO measurements_2026_03 (device_id, recorded_at, reading)
VALUES (1, '2026-03-05 10:00+00', 21.7);
ALTER TABLE measurements_2026_03 ADD CONSTRAINT measurements_2026_03_range
CHECK (recorded_at >= '2026-03-01' AND recorded_at < '2026-04-01');
ALTER TABLE measurements ATTACH PARTITION measurements_2026_03
FOR VALUES FROM ('2026-03-01') TO ('2026-04-01');Here is what happens at ATTACH PARTITION:
- PostgreSQL checks that the table's columns match the parent's. The names and types must be identical. The column order may differ, and extra columns are not allowed.
- It checks that the new bounds do not overlap an existing partition. If they do, you get
partition "..." would overlap partition "...". - It must prove that every existing row satisfies the partition constraint. By default it does this by scanning the whole table.
Step 3 is the expensive one. The scan is skipped when the table already has a valid CHECK constraint that implies the partition constraint. That is why the example adds measurements_2026_03_range before attaching.
If a row violates the bounds, the attach fails with partition constraint of relation "..." is violated by some row, and nothing changes.
Make the check constraint skip the scan
A few details decide whether the scan is really skipped:
- The constraint must be validated. A
NOT VALIDconstraint does not count. NOT NULLon the partition key column also matters. Create the table withLIKE, which copiesNOT NULL, or add the constraint yourself.- The check must imply the partition bounds, not just resemble them. For ranges, use the same lower-inclusive, upper-exclusive form the partition uses.
- Bounds written as literals for a
timestamptzcolumn are interpreted in the session'sTimeZonesetting. Use the same setting for theCHECKand for theATTACH, or write explicit offsets such as'2026-03-01 00:00+00'.
After the attach succeeds, the CHECK constraint is redundant. You can drop it with ALTER TABLE measurements_2026_03 DROP CONSTRAINT measurements_2026_03_range;.
Indexes during attach
If the parent has a partitioned index, attaching a partition needs a matching index on it. PostgreSQL reuses an existing index that matches the parent's definition. If none exists, it builds one during the attach, while holding locks. For a large table, create the matching index on the standalone table first. Creating the standalone table with LIKE ... INCLUDING INDEXES copies the parent's index definitions. Unique indexes and the primary key are required to match.
Locks taken by ATTACH
| Object | Lock during `ATTACH PARTITION` |
|---|---|
| Parent table | `SHARE UPDATE EXCLUSIVE` (PostgreSQL 12 and later) |
| Table being attached | `ACCESS EXCLUSIVE` |
| Default partition, if any | `ACCESS EXCLUSIVE` |
SHARE UPDATE EXCLUSIVE on the parent does not block ordinary reads and writes on it. The lock on the new table is harmless because nobody else uses it yet. The default partition is the problem case, as the next section explains.
Attaching when a default partition exists
A default partition holds rows that fit no other partition. Adding a new partition takes some of that key space. PostgreSQL therefore has to prove that the default partition contains no row that belongs in the new range. Without that proof it scans the default partition while holding ACCESS EXCLUSIVE on it, which blocks queries against that partition.
If the default partition has a CHECK constraint that excludes the new range, the scan is skipped. Otherwise, a large default partition makes every attach slow.
CREATE TABLE measurements_default PARTITION OF measurements DEFAULT;
INSERT INTO measurements (device_id, recorded_at, reading)
VALUES (1, '2030-06-01', 20.5);
SELECT tableoid::regclass, count(*) FROM measurements GROUP BY 1;Now suppose you try to attach a partition for 2030-06 while that row sits in the default partition:
CREATE TABLE measurements_2030_06 (LIKE measurements INCLUDING DEFAULTS INCLUDING CONSTRAINTS);
ALTER TABLE measurements ATTACH PARTITION measurements_2030_06
FOR VALUES FROM ('2030-06-01') TO ('2030-07-01');This fails with updated partition constraint for default partition "measurements_default" would be violated by some row. The row must first be moved out of the default partition, for example by deleting it and inserting it into the new table before attaching.
The practical lesson is to create partitions before the data arrives. Keep the default partition empty, and treat any rows in it as an alert.
Detaching a partition
ALTER TABLE measurements DETACH PARTITION measurements_2026_01;The partition becomes an ordinary table with all its rows. Queries on the parent no longer see it. The plain form takes ACCESS EXCLUSIVE on the parent, so it waits for every running query on the parent and blocks new ones while it waits. On a busy system this can stall the whole table behind one long query.
DETACH PARTITION ... CONCURRENTLY
PostgreSQL 14 added a non-blocking variant:
ALTER TABLE measurements DETACH PARTITION measurements_2026_01 CONCURRENTLY;
DROP TABLE measurements_2026_01;
ANALYZE measurements;It uses only SHARE UPDATE EXCLUSIVE on the parent, and works in two transactions. The first marks the partition as "detach pending". After waiting for queries that could still see it, the second completes the detach. This has three restrictions:
- It cannot run inside a transaction block, so a migration tool that wraps every file in
BEGIN ... COMMITwill reject it. - It is not allowed if the parent has a default partition. In the examples above, you would have to drop
measurements_defaultfirst, or use the plain form. - If the session is cancelled or the connection drops between the two transactions, the partition stays in the detach-pending state. Complete it with
ALTER TABLE measurements DETACH PARTITION measurements_2026_01 FINALIZE;. Until then, the table cannot be attached again or dropped normally.
What you can do with a detached table
DROP TABLEit to delete old data instantly, with no bulkDELETEand no vacuum work.- Dump it with
pg_dump -tand move it to cheaper storage, then drop it. - Keep it as a normal table for occasional queries, or reattach it later with the same bounds.
- Move it to another tablespace or change its storage settings, then reattach it.
A routine for a rolling window
For a table partitioned by month, the monthly job looks like this:
- Create the next month's table with
LIKE, then add itsCHECKconstraint and any needed indexes. - Load or backfill any data it needs.
ATTACH PARTITIONit, ahead of the first row's arrival.DETACH PARTITION ... CONCURRENTLYthe partition that has left the retention window.- Archive and drop the detached table.
ANALYZEthe parent, because autovacuum does not analyze a partitioned parent table. Statistics on the parent are only refreshed by a manualANALYZE.
Common failures
| Error or symptom | Cause | Fix |
|---|---|---|
| `partition "x" would overlap partition "y"` | The new bounds intersect an existing partition. | Check bounds. Remember the upper bound is excluded. |
| `partition constraint of relation "x" is violated by some row` | A row lies outside the new bounds. | Move or delete the offending rows, then retry. |
| `updated partition constraint for default partition ... would be violated` | Rows that belong in the new range are in the default partition. | Move them out of the default partition first. |
| Attach is slow | No validated `CHECK`, a missing index on the new table, or a large default partition. | Add the `CHECK`, prebuild indexes, and keep the default partition small. |
| `DETACH ... CONCURRENTLY cannot run inside a transaction block` | The migration tool wraps the statement in a transaction. | Run it outside a transaction. |
| Detach waits and everything queues up | Plain detach waiting for a long query on the parent. | Use `CONCURRENTLY`, or set `lock_timeout` and retry. |
Exercise
You need to add a partition for April 2026 to a monthly range-partitioned measurements table that has a large default partition and about 200 million rows ready to load. Describe the steps that keep the attach fast, and name two things that would make it slow.
Show answer
Create a standalone table with CREATE TABLE ... (LIKE measurements INCLUDING DEFAULTS INCLUDING CONSTRAINTS INCLUDING INDEXES), load the rows into it, and add a validated CHECK (recorded_at >= '2026-04-01' AND recorded_at < '2026-05-01'). Then run ATTACH PARTITION ... FOR VALUES FROM ('2026-04-01') TO ('2026-05-01'). The CHECK lets PostgreSQL skip scanning the new table, and the pre-built indexes avoid an index build during the attach. Two things make it slow: no validated CHECK on the new table, which forces a full scan under ACCESS EXCLUSIVE, and a large default partition without a CHECK that excludes April, which forces a scan of the default partition. A missing matching index on the new table is also acceptable as a second slow factor.
Exercise
Your migration tool runs every script inside a transaction, and ALTER TABLE measurements DETACH PARTITION measurements_2026_01 CONCURRENTLY; fails. Give two reasons it could fail and how to tell them apart.
Show answer
One reason is that the statement is inside a transaction block, so PostgreSQL reports that DETACH ... CONCURRENTLY cannot run inside a transaction block. The fix is to run it outside a transaction. The other reason is that measurements has a default partition, which makes concurrent detach unsupported. The error message names the default partition. In that case you drop or empty the default partition, or use the plain DETACH PARTITION.