Sub topic 4
Partitioning by Ranges
Assume you know basic PostgreSQL table definitions, constraints, indexes, and the basics of reading a query plan. This chapter focuses on range partitioning, where PostgreSQL assigns rows to partitions according to ordered value intervals.
How range partitioning works
Range partitioning is useful when values have a natural order. Dates are a common choice because applications often query recent data or remove old data by time period.
A range partition has a lower bound and an upper bound. PostgreSQL includes the lower bound and excludes the upper bound. In other words, FROM ('2026-01-01') TO ('2026-02-01') accepts dates from January 1 through January 31.
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);
CREATE TABLE orders_2026_01
PARTITION OF orders
FOR VALUES FROM ('2026-01-01') TO ('2026-02-01');
CREATE TABLE orders_2026_02
PARTITION OF orders
FOR VALUES FROM ('2026-02-01') TO ('2026-03-01');
CREATE TABLE orders_2026_03
PARTITION OF orders
FOR VALUES FROM ('2026-03-01') TO ('2026-04-01');
INSERT INTO orders (order_id, customer_id, order_date, amount)
VALUES
(1, 42, DATE '2026-01-15', 19.99),
(2, 42, DATE '2026-02-01', 35.50);The orders table is the logical parent. The three child tables store the actual rows. An insert into orders is routed to the child whose bounds contain order_date. The row dated February 1 goes to orders_2026_02, because February 1 is excluded from the January partition and included in the February partition.
Bounds, gaps, and query pruning
Partitions for one parent cannot have overlapping bounds. However, they can leave gaps. With the example above, a row dated April 1 has no matching partition, so PostgreSQL rejects the insert unless you create another partition or a default partition.
The same bounds help PostgreSQL prune partitions. For example, a query restricted to February dates can avoid scanning the January and March partitions.
EXPLAIN (COSTS OFF)
SELECT order_id, amount
FROM orders
WHERE order_date >= DATE '2026-02-10'
AND order_date < DATE '2026-02-15';Look for a plan that accesses only orders_2026_02. Pruning depends on PostgreSQL recognizing a relationship between the query predicate and the partition bounds. Expressions that hide the partition key can make pruning less effective.
Common mistakes
- Using an inclusive upper bound in application logic and accidentally duplicating boundary values.
- Forgetting to create the next partition before new data arrives.
- Choosing a key that queries rarely filter on, which limits partition pruning.
- Assuming partitioning automatically improves every query. It helps most when queries can eliminate whole partitions.
Exercise
Which partition receives a row with order_date = DATE '2026-03-01'?
Show answer
orders202603. Its lower bound is March 1, and its upper bound is April 1, which is exclusive.