Partitioned Index Auto Attaches Children
CREATE INDEX on a partitioned parent builds and attaches a child index per partition, or defers with ON ONLY until every partition attaches.
Code
-- 在分区父表上 CREATE INDEX:自动为每个分区建子索引并挂载(PG 11+)
CREATE TABLE measurements (taken_at timestamptz NOT NULL, value numeric)
PARTITION BY RANGE (taken_at);
CREATE TABLE m2026_10 PARTITION OF measurements
FOR VALUES FROM ('2026-10-01') TO ('2026-11-01');
CREATE TABLE m2026_11 PARTITION OF measurements
FOR VALUES FROM ('2026-11-01') TO ('2026-12-01');
CREATE INDEX measurements_taken_idx ON measurements (taken_at);
-- 父索引是分区索引:每个分区都挂了一个对应子索引
SELECT count(*) AS child_indexes
FROM pg_inherits
WHERE inhparent = 'measurements_taken_idx'::regclass; -- 2
-- ON ONLY:先建父索引但保持 INVALID,等分区逐个 ATTACH
CREATE INDEX taken_partial_idx ON ONLY measurements (taken_at);
SELECT indisvalid FROM pg_index
WHERE indexrelid = 'taken_partial_idx'::regclass; -- f
CREATE INDEX m2026_10_taken_idx ON m2026_10 (taken_at);
ALTER INDEX taken_partial_idx ATTACH PARTITION m2026_10_taken_idx;
SELECT indisvalid FROM pg_index
WHERE indexrelid = 'taken_partial_idx'::regclass; -- 仍为 f:还有分区未挂
CREATE INDEX m2026_11_taken_idx ON m2026_11 (taken_at);
ALTER INDEX taken_partial_idx ATTACH PARTITION m2026_11_taken_idx;
SELECT indisvalid FROM pg_index
WHERE indexrelid = 'taken_partial_idx'::regclass; -- t:全部分区已挂载Automatic attach
CREATE INDEX measurements_taken_idx ON measurements (taken_at) on the partitioned parent builds one child index per partition and attaches it — the pg_inherits query against the parent index counts child_indexes: 2 for the two partitions.
Deferred attach with ON ONLY
CREATE INDEX taken_partial_idx ON ONLY measurements builds the parent index as INVALID (indisvalid: f). Each child index is then built and attached with ALTER INDEX … ATTACH PARTITION; the validity flip to true happens only after the last partition attaches.
Why the deferred form exists
Building all partitions in one statement can hold locks too long; ON ONLY splits the work into per-partition steps, each short, with the parent turning valid once the set completes.
Interactive Tools for This Topic
FAQ
- When does the ON ONLY parent index become valid?
- Only after every partition's child index has been attached via ALTER INDEX ... ATTACH PARTITION; before that indisvalid stays false.
- What does CREATE INDEX on a partitioned parent do automatically?
- It builds and attaches a matching child index for every existing partition, which the pg_inherits count of 2 confirms.
Report a problem with this exampleOpens a pre-filled issue on GitHub.