Use pg_partman to Partition Tables
Create and maintain time-based or ID-based partition sets with the pg_partman extension, so that new partitions exist before rows arrive and old ones are retired on schedule.
Before You Start
Open a
psqlsession asavnadmin. See Connect with psql.This page uses the
pg_partman5 interface. Check the version offered on your service:SELECT name, default_version FROM pg_available_extensions WHERE name = 'pg_partman';If it starts with
4, thecreate_parent()arguments differ; follow the pg_partman documentation of that version.Partitions are created and dropped by a maintenance routine that something has to call. This page uses pg_cron.
Warning
Examples written for pg_partman 4 fail on version 5. p_type := 'native' is rejected with
ERROR: native is not a valid partitioning type for pg_partman, and interval keywords such as
'daily' with ERROR: Special partition interval values from old pg_partman versions (daily) are no longer supported. Use an interval such as '1 day'.
Enable the Extension
Create a dedicated schema, then the extension in it:
CREATE SCHEMA partman;CREATE EXTENSION pg_partman SCHEMA partman;Without SCHEMA, the extension installs into your current schema, usually public. It cannot be
moved later: ALTER EXTENSION pg_partman SET SCHEMA fails with
ERROR: extension "pg_partman" does not support SET SCHEMA. To change the schema, drop the
extension and create it again.
The configuration table partman.part_config and the functions such as
partman.create_parent(), partman.run_maintenance_proc() and partman.show_partitions() live
in the partman schema.
Create a Time-Based Partition Set
pg_partman 5 manages declarative partitioning: declare the parent table as partitioned, then
register it.
Create the parent table, partitioned by range on the time column:
CREATE TABLE public.events ( id bigint GENERATED BY DEFAULT AS IDENTITY, created_at timestamptz NOT NULL, payload jsonb ) PARTITION BY RANGE (created_at);A primary key or unique constraint must include the partition key.
PRIMARY KEY (id)alone fails withunique constraint on partitioned table must include all partitioning columns; usePRIMARY KEY (id, created_at).Use
GENERATED BY DEFAULTrather thanGENERATED ALWAYSfor an identity column.partman.partition_data_proc(), used later on this page, copiesidvalues and fails on aGENERATED ALWAYScolumn withcannot insert a non-DEFAULT value into column "id".Register it:
SELECT partman.create_parent( p_parent_table := 'public.events', p_control := 'created_at', p_interval := '1 day', p_premake := 4 );Parameters:
p_parent_table: schema-qualified parent table, declaredPARTITION BY RANGE.p_control: partition key column.p_interval: width of one partition, such as'1 hour','1 day'or'1 week'.p_premake: number of partitions kept ready ahead of the current one. Default4.
List the partitions. With
p_premake := 4there are nine: four in the past, the current one and four ahead.SELECT partition_schemaname, partition_tablename FROM partman.show_partitions('public.events') ORDER BY partition_tablename;Names follow the parent and the start of the period, for example
events_p20261110.create_parent()also creates a default partition,events_default, for rows that fit no other partition.show_partitions()lists it only withp_include_default := true.Review the configuration:
SELECT parent_table, control, partition_type, partition_interval, premake, automatic_maintenance, retention, retention_keep_table FROM partman.part_config;
Rows are routed to the matching partition. Check with the tableoid system column:
INSERT INTO public.events (created_at, payload)
VALUES (now(), '{"action": "login"}'),
(now() - interval '1 day', '{"action": "signup"}');SELECT tableoid::regclass AS partition, id, created_at
FROM public.events
ORDER BY created_at;A query that filters on created_at skips the partitions that cannot match, shown as
Subplans Removed in the plan:
EXPLAIN
SELECT count(*)
FROM public.events
WHERE created_at >= now() - interval '2 days';Create an ID-Based Partition Set
Use an integer partition key and an interval expressed as a number of values:
CREATE TABLE public.metrics (
id bigint GENERATED BY DEFAULT AS IDENTITY,
val double precision
) PARTITION BY RANGE (id);SELECT partman.create_parent(
p_parent_table := 'public.metrics',
p_control := 'id',
p_interval := '100000',
p_premake := 2
);Each partition holds 100000 IDs. The set starts with metrics_p0, metrics_p100000,
metrics_p200000 and metrics_default. An ID-based set advances with the highest stored value,
not with the clock.
Run Maintenance on a Schedule
Maintenance creates the next partitions and applies retention. Run it once by hand:
CALL partman.run_maintenance_proc();run_maintenance_proc() processes every set and takes no table argument. To process one set,
use the function instead:
SELECT partman.run_maintenance(p_parent_table := 'public.events', p_analyze := true);Then schedule maintenance with pg_cron. pg_cron lives in defaultdb, so name the database
that holds the partition sets:
SELECT cron.schedule_in_database(
'partman-maintenance',
'0 * * * *',
$$CALL partman.run_maintenance_proc()$$,
'DATABASE_NAME'
);Parameters:
DATABASE_NAME: database wherepg_partmanis installed. Run the statement indefaultdb.
If the partition sets are in defaultdb itself, cron.schedule() with the same command is
enough. A job that runs in a database without pg_partman fails with
ERROR: schema "partman" does not exist. Check the runs:
SELECT jobid, status, return_message, start_time
FROM cron.job_run_details
WHERE jobid IN (SELECT jobid FROM cron.job WHERE jobname = 'partman-maintenance')
ORDER BY start_time DESC
LIMIT 5;Keep the maintenance interval well under p_premake times p_interval. With daily partitions
and p_premake := 4, hourly maintenance leaves four days of margin.
Two partman.part_config columns change what maintenance does for a set:
infinite_time_partitions: with the defaultfalse, a time-based set only advances while rows arrive. Set it totrueto create partitions from the clock even without data.automatic_maintenance: set tooffto haverun_maintenance_proc()skip the set. A call torun_maintenance(p_parent_table := ...)still processes it.
Rows in the Default Partition
When no partition matches a row, for example because maintenance did not run for a while, the
row goes to the default partition. Maintenance then skips that set, with
WARNING: pg_partman maintenance skipped partition set for parent table public.events: updated partition constraint for default partition "events_default" would be violated by some row, and
no new partitions are created for it. Find affected sets:
SELECT * FROM partman.check_default();Move the rows into proper partitions, created as needed:
CALL partman.partition_data_proc(
p_parent_table := 'public.events',
p_wait := 0
);Apply a Retention Policy
Retention is set in partman.part_config:
UPDATE partman.part_config
SET retention = '90 days',
retention_keep_table = false
WHERE parent_table = 'public.events';Parameters:
retention: an interval for time-based sets, or a number of values for ID-based sets. Partitions entirely older than this are retired at the next maintenance run.retention_keep_table:true(the default) detaches old partitions and keeps them as tables;falsedrops them.
Caution
With retention_keep_table = false, the next maintenance run drops data without asking. There
is no in-place restore: getting the data back means creating a new service from a point in
time before the drop, see
Fork a service. Start with
retention_keep_table = true, check which partitions are detached, then switch.
To move retired partitions into another schema instead, create the schema first and set
retention_schema:
CREATE SCHEMA archive;UPDATE partman.part_config
SET retention = '90 days',
retention_keep_table = true,
retention_schema = 'archive'
WHERE parent_table = 'public.events';Partition an Existing Table
create_parent() only accepts a partitioned table, so move the data of an ordinary table into a
new parent. For public.measurements, partitioned on recorded_at:
Rename the current table:
ALTER TABLE public.measurements RENAME TO measurements_old;Create the new parent with the original name and columns,
PARTITION BY RANGE (recorded_at), and register it:SELECT partman.create_parent( p_parent_table := 'public.measurements', p_control := 'recorded_at', p_interval := '1 day', p_premake := 2 );Move the rows. The procedure commits batch by batch and creates the partitions the old rows need, however far back they go:
CALL partman.partition_data_proc( p_parent_table := 'public.measurements', p_source_table := 'public.measurements_old', p_wait := 0 );Update statistics:
VACUUM ANALYZE public.measurements;Compare row counts, then drop the empty
public.measurements_old.
To go back to a plain table, create the target table and undo the partitioning:
CREATE TABLE public.metrics_plain (LIKE public.metrics);CALL partman.undo_partition_proc(
p_parent_table := 'public.metrics',
p_target_table := 'public.metrics_plain',
p_wait := 0,
p_keep_table := false
);The rows move to public.metrics_plain, the partitions are dropped and the set is removed from
partman.part_config. The empty parent table remains; drop it when you no longer need it.
Stop Managing a Partition Set
DELETE FROM partman.part_config
WHERE parent_table = 'public.events';The parent and its partitions stay as they are and are no longer maintained.