Sub topic 12
Retention, ANALYZE and routine maintenance
This chapter assumes you can create range partitioned tables, read basic EXPLAIN output, and attach and detach partitions as covered earlier. It shows how to run a partitioned table over months and years: removing old data, creating future partitions, and keeping statistics and storage healthy.
Why retention is a partitioning strength
Without partitioning, removing old rows means a bulk DELETE. That DELETE scans rows, writes a WAL record for each one, and leaves dead tuples. Autovacuum then has to clean those up, and the table file does not shrink.
With range partitioning by time, each partition holds one period. Removing a period means detaching the partition and dropping it. DROP TABLE deletes the partition's files. It does not touch rows one by one, so it is fast and returns disk space to the operating system immediately.
| Approach | Row-by-row work | Dead tuples left | Disk space returned |
|---|---|---|---|
| `DELETE FROM ... WHERE recorded_at < ...` | Yes | Yes, until vacuumed | Usually not, without a rewrite |
| `DETACH PARTITION` then `DROP TABLE` | No | None | Yes, immediately |
The retention routine
The standard routine for the measurements table has three parts, repeated on a schedule:
- Create partitions for upcoming periods before any data needs them.
- Detach and drop (or archive) partitions older than the retention window.
- Refresh statistics on the parent table.
Dropping an old partition
ALTER TABLE measurements DETACH PARTITION measurements_2026_01 CONCURRENTLY;
DROP TABLE measurements_2026_01;
ANALYZE measurements;DETACH PARTITION ... CONCURRENTLY is available from PostgreSQL 14. It takes a weaker lock than a plain detach, so queries and inserts on the parent keep running. It cannot run inside a transaction block. If you run it from a script, make sure the client is not wrapping statements in BEGIN and COMMIT.
A plain DETACH PARTITION (without CONCURRENTLY) takes an ACCESS EXCLUSIVE lock on the parent. Every query on the parent waits until the detach finishes. The statement is quick, but it can queue behind a long-running query, and then new queries queue behind it.
Archiving instead of dropping
Detaching does not delete data. The detached partition becomes an ordinary table. Before you drop it, you can export it or move it to cheaper storage:
ALTER TABLE measurements DETACH PARTITION measurements_2026_01 CONCURRENTLY;
COPY measurements_2026_01 TO '/var/backups/measurements_2026_01.csv' WITH (FORMAT csv, HEADER);
DROP TABLE measurements_2026_01;COPY ... TO a server-side file needs superuser rights or the pg_write_server_files role. From a client machine, use \copy in psql instead. Another option is ALTER TABLE ... SET TABLESPACE to move the old partition to a slower disk and keep it queryable as a standalone table.
Creating future partitions
A partition must exist before rows arrive for its range. If none does and there is no default partition, the insert fails with no partition of relation "measurements" found for row. If there is a default partition, the row goes there instead, which causes its own problem (see the next section).
Create next month's partition ahead of time:
CREATE TABLE IF NOT EXISTS measurements_2026_04 PARTITION OF measurements
FOR VALUES FROM ('2026-04-01') TO ('2026-05-01');Create several periods ahead, such as the next two or three months, so that a missed job does not cause an outage. Because the range bounds are fixed, the statement is deterministic and safe to run repeatedly with IF NOT EXISTS.
Automating the routine
PostgreSQL has no built-in scheduler or automatic partition creation. Common options are:
- A scheduled SQL script run by cron, or by a job runner your organization already uses.
- The
pg_cronextension, which runs SQL on a schedule inside the database. - The
pg_partmanextension, which creates and drops partitions based on a configuration table.
Here is a small PL/pgSQL function that creates the partition for the month containing a given date. It can be called from any scheduler:
CREATE OR REPLACE FUNCTION create_measurements_partition(p_month date)
RETURNS void
LANGUAGE plpgsql
AS $$
DECLARE
start_date date := date_trunc('month', p_month)::date;
end_date date := (date_trunc('month', p_month) + interval '1 month')::date;
part_name text := format('measurements_%s', to_char(start_date, 'YYYY_MM'));
BEGIN
EXECUTE format(
'CREATE TABLE IF NOT EXISTS %I PARTITION OF measurements FOR VALUES FROM (%L) TO (%L)',
part_name, start_date, end_date
);
END;
$$;
SELECT create_measurements_partition((current_date + interval '1 month')::date);
SELECT create_measurements_partition((current_date + interval '2 months')::date);The function uses format with %I for identifiers and %L for literals, so the generated names and values are quoted safely.
The default partition and maintenance
A default partition catches rows that fit no other partition. That is convenient, but it affects maintenance in two ways.
First, rows in the default partition are easy to miss. If the creation job fails, data silently accumulates there. Monitor it:
SELECT count(*) FROM measurements_default;Second, adding a new partition whose range overlaps rows already in the default partition fails, because PostgreSQL must prove the default partition holds no rows that belong to the new one. It scans the default partition to check, and it holds a strong lock on it while it does so. A large default partition makes partition creation slow and disruptive.
If rows have landed in the default partition, move them out before creating the partition:
BEGIN;
CREATE TEMP TABLE stray AS
SELECT * FROM measurements_default
WHERE recorded_at >= '2026-04-01' AND recorded_at < '2026-05-01';
DELETE FROM measurements_default
WHERE recorded_at >= '2026-04-01' AND recorded_at < '2026-05-01';
CREATE TABLE measurements_2026_04 PARTITION OF measurements
FOR VALUES FROM ('2026-04-01') TO ('2026-05-01');
INSERT INTO measurements SELECT * FROM stray;
COMMIT;The better fix is to create partitions early enough that the default partition stays empty.
Statistics and ANALYZE
The planner depends on table statistics to choose plans. On a partitioned table, statistics live in two places:
- Each partition has its own statistics, which autovacuum keeps current.
- The parent table has statistics describing all partitions together.
Autovacuum does not analyze the parent table. The parent holds no rows itself, so autovacuum never sees changes to it. Without a manual ANALYZE measurements, the parent has no statistics, or stale ones. Queries that need the combined view, such as joins and aggregates that cannot prune down to one partition, can then get poor row estimates.
Run ANALYZE on the parent after large loads, after dropping or attaching partitions, and on a regular schedule:
ANALYZE measurements;This samples rows from all partitions, so on a very large table it takes time. ANALYZE on the parent does not replace analyzing the partitions. For a newly attached partition that was loaded outside the normal path, analyze it directly too:
ANALYZE measurements_2026_03;You can check when statistics were last collected:
SELECT relname, last_analyze, last_autoanalyze
FROM pg_stat_user_tables
WHERE relname LIKE 'measurements%'
ORDER BY relname;The parent table appears in this view with last_analyze filled in only after you have analyzed it manually.
Vacuum and storage
Autovacuum handles each partition independently, using that partition's own dead tuple counts and thresholds. This is another benefit of partitioning. Old partitions that no longer change are rarely touched, while the active partition gets vacuumed as needed.
Some points to watch:
- You can set storage parameters, such as
autovacuum_vacuum_scale_factor, on an individual partition withALTER TABLE measurements_2026_03 SET (...). You cannot set most storage parameters on the partitioned parent. - After a partition stops receiving writes, run a manual
VACUUMon it once. This sets visibility map bits and freezes tuples, which helps index-only scans and avoids later anti-wraparound vacuums on cold data. - Because old partitions are dropped rather than deleted from, you rarely need
VACUUM FULLto reclaim space.
VACUUM (ANALYZE) measurements_2026_03;VACUUM run on the parent table processes every partition. That is convenient for a one-off pass, but it can take a long time on a large hierarchy.
Keeping the partition count under control
Each partition is a real table with its own catalog entries, files, and indexes. Planning time grows with the number of partitions that survive pruning, and memory use grows with the number of open relations. Retention keeps the count bounded, which is another reason to drop old partitions on schedule instead of leaving them indefinitely.
Choose partition sizes with this in mind. Daily partitions over ten years give about 3,650 partitions, which is likely too many. Monthly partitions over the same period give 120.
A simple health query lists partitions with their sizes:
SELECT c.relname AS partition_name,
pg_size_pretty(pg_total_relation_size(c.oid)) AS total_size
FROM pg_inherits i
JOIN pg_class c ON c.oid = i.inhrelid
WHERE i.inhparent = 'measurements'::regclass
ORDER BY c.relname;A maintenance cycle at a glance
Common mistakes
- Relying on autovacuum to analyze the parent table. It does not.
- Forgetting to create future partitions, so inserts fail or fill the default partition.
- Running
DETACH ... CONCURRENTLYinside a transaction block, which raises an error. - Dropping a partition without confirming that its range is outside the retention window.
- Using daily partitions for data that could be monthly, producing thousands of partitions.
Exercise
Your retention job drops partitions older than 12 months. The job ran successfully last night, but today the planner picks a poor plan for a join between the parent measurements table and a devices table. Row estimates for measurements look far too low. What is the likely cause, and what command fixes it?
Show answer
Autovacuum never analyzes the partitioned parent, and dropping partitions changes the data the parent's statistics describe. The parent's statistics are missing or stale, so the planner underestimates rows. Run ANALYZE measurements; on the parent, and add it to the end of the retention routine so it runs after every drop or attach.
Exercise
An insert for a row dated 2026-05-14 fails with no partition of relation "measurements" found for row. The table has no default partition. Write the statement that fixes the immediate problem, and describe one change to the routine that prevents it from recurring.
Show answer
Run CREATE TABLE measurements_2026_05 PARTITION OF measurements FOR VALUES FROM ('2026-05-01') TO ('2026-06-01'); and retry the insert. To prevent it, schedule a job that creates partitions two or three periods ahead, using CREATE TABLE IF NOT EXISTS so it is safe to repeat.