Sub topic 16
Retention, Archiving, and Maintenance
Assume you know basic PostgreSQL table definitions, constraints, indexes, and query plans. This chapter focuses on operating an existing partitioned table over time.
Plan the partition lifecycle
Partitioning makes retention work easier because a time period can often be removed as one table. Before creating partitions, decide:
- How far ahead to create future partitions.
- How long data stays in the active database.
- Whether older data is archived, detached, or deleted.
- Who or what creates and removes partitions.
- How indexes, backups, and permissions apply to each partition.
A useful policy separates data into active, archive, and removal stages:
| Stage | Typical action | Main concern |
|---|---|---|
| Active | Query and maintain normally | Performance |
| Archive | Detach and copy or retain separately | Recoverability |
| Removal | Drop the partition | Verification |
Detach before removal
Detaching removes a partition from the logical parent without immediately deleting its table. This provides a safer checkpoint for archiving or inspection.
ALTER TABLE orders
DETACH PARTITION orders_2025_12;
-- After confirming backups and archive requirements:
DROP TABLE orders_2025_12;After detaching, queries against orders no longer see rows in orders_2025_12. The detached table remains available for separate queries, export, backup, or transfer to another system.
Dropping a partition is usually much faster than deleting matching rows from the parent. A large DELETE can generate substantial write-ahead log, hold row locks, create dead tuples, and require vacuum work. Dropping a table avoids that row-by-row cleanup.
Maintain active partitions
Partitioning does not remove normal database maintenance. Run ANALYZE after large loads so the planner has current statistics. Run VACUUM according to the database's normal policy, especially after updates or deletes within active partitions.
ANALYZE orders_2026_01;
VACUUM (ANALYZE) orders_2026_02;Indexes also require planning. An index defined on the partitioned parent creates corresponding indexes for existing partitions and guides index creation for future partitions. Check index size and usage per partition. An index that helps recent queries may be unnecessary on immutable archive partitions.
Automate safely
A scheduled job can create the next partition before its first expected row arrives. It should also check that:
- The partition does not already exist.
- Bounds do not overlap.
- The operation succeeds before ingestion depends on it.
- A default partition is not silently accumulating unexpected rows.
- Retention actions have backup and approval records.
Exercise
Why is detaching a partition safer than immediately dropping it?
Show answer
Detaching preserves the table as an independent object, allowing backup, export, and validation before irreversible removal.