Browse topics

Declarative table partitioning

Version
19
Since
10
Review
Draft

Summary#

A partitioned parent routes inserts to child tables using the partition key. Query the parent to read across partitions. When a filter rules out a partition's bounds, PostgreSQL can skip that partition.

Syntax#

sql
CREATE TABLE parent (column_definitions)
PARTITION BY RANGE (range_key);

CREATE TABLE child PARTITION OF parent
FOR VALUES FROM (lower_bound) TO (upper_bound);

Example#

The output below is from PostgreSQL 19.0, produced with psql -X -q -A -P null=NULL -v ON_ERROR_STOP=1 -f example.sql in a scratch database. The script rolls back at the end, so it leaves nothing behind.

sql
BEGIN;
SET LOCAL DateStyle = 'ISO, YMD';

CREATE TEMPORARY TABLE meter_readings (
    reading_on date NOT NULL,
    meter_id   integer NOT NULL,
    units      integer NOT NULL,
    PRIMARY KEY (reading_on, meter_id)
) PARTITION BY RANGE (reading_on);

CREATE TEMPORARY TABLE meter_readings_june PARTITION OF meter_readings
FOR VALUES FROM ('2026-06-01') TO ('2026-07-01');

CREATE TEMPORARY TABLE meter_readings_july PARTITION OF meter_readings
FOR VALUES FROM ('2026-07-01') TO ('2026-08-01');

INSERT INTO meter_readings VALUES
    ('2026-06-30', 8, 34),
    ('2026-07-01', 8, 36);

SELECT reading_on, units, tableoid::regclass AS stored_in
FROM meter_readings
ORDER BY reading_on, meter_id;

ROLLBACK;

Expected output#

Text
reading_on|units|stored_in
2026-06-30|34|meter_readings_june
2026-07-01|36|meter_readings_july
(2 rows)

Common mistakes#

A range includes its lower bound and excludes its upper bound. Create a matching partition before inserting a row, or provide a default partition to catch unmatched rows. A primary key or unique constraint on the parent must include every partition key column and requires a partition key made of columns.

Version applicability#

PostgreSQL 10 added declarative range and list partitioning. PostgreSQL 11 added primary keys on partitioned parents and default partitions. The example uses a parent primary key.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0