Sub topic 1
Why partition a PostgreSQL table?
Prerequisites
This chapter assumes you know basic SQL, can define tables with primary keys and constraints, and can run queries from psql or another client. You should also understand how an index speeds up a query.
Why partition
Partitioning splits one large logical table into smaller physical tables called partitions. A query that filters on the partition key reads only the partitions it needs. Removing old data also becomes cheap: dropping a partition is much faster than deleting millions of rows.
The declarative partitioned-table model
With declarative partitioning, the parent table stores no rows itself. You declare a partition key with PARTITION BY, then create child partitions that each cover part of the key space. Applications query the parent, and PostgreSQL routes each row to the right child.
CREATE TABLE orders (
order_id bigint NOT NULL,
customer_id bigint NOT NULL,
order_date date NOT NULL,
amount numeric(12, 2) NOT NULL
) PARTITION BY RANGE (order_date);Choosing a partition key
Pick a column that appears in most WHERE clauses and spreads rows evenly. Dates suit logs and orders. A column that queries rarely filter on gives no pruning benefit.
Partitioning by ranges
Range partitioning assigns rows by interval. The lower bound is inclusive and the upper bound is exclusive.
CREATE TABLE orders_2026_01
PARTITION OF orders
FOR VALUES FROM ('2026-01-01') TO ('2026-02-01');Partitioning by explicit values
List partitioning assigns rows to a fixed set of values, such as a status or region code.
CREATE TABLE tickets (
ticket_id bigint NOT NULL,
status text NOT NULL
) PARTITION BY LIST (status);
CREATE TABLE tickets_open
PARTITION OF tickets
FOR VALUES IN ('open', 'pending');Partitioning by hash
Hash partitioning spreads rows across a fixed number of partitions using a hash of the key. It balances data well when no natural range exists. It does not help range queries, because neighboring key values land in different partitions.
CREATE TABLE events (
event_id bigint NOT NULL,
payload jsonb NOT NULL
) PARTITION BY HASH (event_id);
CREATE TABLE events_0 PARTITION OF events
FOR VALUES WITH (MODULUS 4, REMAINDER 0);Defining bounds without gaps or overlaps
PostgreSQL rejects range partitions whose bounds overlap. Each partition's upper bound should equal the next partition's lower bound. A gap between bounds means rows in that gap fail to insert unless a default partition exists.
Exercise
In a range partition defined FOR VALUES FROM ('2026-01-01') TO ('2026-02-01'), is the value '2026-02-01' stored in this partition?
Show answer
No. The lower bound is inclusive and the upper bound is exclusive, so '2026-02-01' belongs to the next partition.