Database

pg_partman: partition management


pg_partman is a Postgres extension that automates the creation and maintenance of partitions for tables using Postgres native partitioning.

Enable the extension#

To enable pg_partman, create a dedicated schema for it and enable the extension there.

1
create schema if not exists partman;
2
create extension if not exists pg_partman with schema partman;

Create a partitioned table#

pg_partman requires your parent table to already be declared as a partitioned table.

1
create table public.messages (
2
id bigint generated by default as identity,
3
sent_at timestamptz not null,
4
sender_id uuid,
5
recipient_id uuid,
6
body text,
7
primary key (sent_at, id)
8
)
9
partition by range (sent_at);

Set up partitioning#

You configure the parent table using partman.create_parent(). The function takes an ACCESS EXCLUSIVE lock briefly while it creates the initial partitions.

Time-based partitions#

1
select partman.create_parent(
2
p_parent_table := 'public.messages',
3
p_control := 'sent_at',
4
p_type := 'range',
5
p_interval := '7 days',
6
p_premake := 7,
7
p_start_partition := '2025-01-01 00:00:00'
8
);

Integer-based partitions#

1
create table public.events (
2
id bigint generated by default as identity,
3
inserted_at timestamptz not null default now(),
4
payload jsonb,
5
primary key (id)
6
)
7
partition by range (id);
8
9
select partman.create_parent(
10
p_parent_table := 'public.events',
11
p_control := 'id',
12
p_type := 'range',
13
p_interval := '100000'
14
);

Running maintenance#

It’s important to call pg_partman maintenance regularly so future partitions are pre-created and retention policies are applied.

1
call partman.run_maintenance_proc();

To automate this, schedule it using pg_cron.

1
create extension if not exists pg_cron;
2
3
select
4
cron.schedule('@hourly', $$call partman.run_maintenance_proc()$$);

Resources#