Partition maintenance
Overview
Partition lifecycle operations add future ranges, attach validated historical tables, detach old partitions for archiving, and drop data only after retention and backup requirements are satisfied. PostgreSQL ATTACH PARTITION validates compatibility and bounds; a matching validated CHECK can avoid the partition validation scan. Locks still matter, including default-partition checks. DETACH keeps a standalone table; DROP removes it. Never run retention DDL against production for practice.
First example
BEGIN;DROP VIEW pt_reporting;CREATE VIEW pt_reporting AS SELECT * FROM pt_all UNION ALL SELECT * FROM pt_archive;SELECT COUNT(*),SUM(amount) FROM pt_reporting;ROLLBACK;Observed SQLite result (rows in JSON):
[ [ 7, 280 ]]How it works
The read-only reporting view initially references both active tables. Replacing it in a transaction with an expanded UNION ALL includes the archive; replacing it with only the late table excludes early rows without deleting them. Both examples roll back their DDL. This is a reporting-view membership analogy, not native ATTACH or DETACH, and does not change the insert-routing trigger.
Practical example
BEGIN;DROP VIEW pt_reporting;CREATE VIEW pt_reporting AS SELECT * FROM pt_late;SELECT (SELECT COUNT(*) FROM pt_reporting),(SELECT COUNT(*) FROM pt_early);ROLLBACK;Observed SQLite result (rows in JSON):
[ [ 2, 4 ]]Practice and mistakes
Practice: compare row counts and sums before and after excluding the early range, then inspect the original table. Hint 1: membership is not destruction. Hint 2: validate boundaries and dependencies before attaching. Local indexes require maintenance; global index behavior varies by engine.
PostgreSQL 17 example — NOT RUN
BEGIN;CREATE TEMP TABLE bm_pt(day integer NOT NULL,id integer NOT NULL,PRIMARY KEY(day,id)) PARTITION BY RANGE(day);CREATE TEMP TABLE bm_pt_early PARTITION OF bm_pt FOR VALUES FROM (1) TO (11);CREATE TEMP TABLE bm_pt_late PARTITION OF bm_pt FOR VALUES FROM (11) TO (21);INSERT INTO bm_pt VALUES (1,1),(5,2),(10,3),(10,4),(11,5),(20,6);CREATE TEMP TABLE bm_pt_archive (LIKE bm_pt INCLUDING ALL);ALTER TABLE bm_pt_archive ADD CHECK(day>=21 AND day<31);INSERT INTO bm_pt_archive VALUES(21,7);ALTER TABLE bm_pt ATTACH PARTITION bm_pt_archive FOR VALUES FROM (21) TO (31);SELECT COUNT(*) FROM bm_pt;ALTER TABLE bm_pt DETACH PARTITION bm_pt_archive;SELECT COUNT(*) FROM bm_pt_archive;ROLLBACK;Expected result, not executed: "Counts 7 then 1; detached table retains its row."