Sub topic 3
Range partitioning by date
This chapter assumes you can write CREATE TABLE, INSERT and SELECT, and that you know what a primary key is. It also assumes you can read a basic EXPLAIN plan. It covers how range partitioning works, how to write correct bounds, and the mistakes that cause errors or surprising data placement.
What range partitioning does
Range partitioning divides a table by continuous, non-overlapping intervals of the partition key. Dates and timestamps are the most common key, because time-series data is usually written in time order, queried over a time window, and deleted by age.
You create a parent table with PARTITION BY RANGE. The parent stores no rows itself. Each partition is a separate table that holds the rows whose key falls in its interval.
CREATE TABLE measurements (
device_id int NOT NULL,
recorded_at timestamptz NOT NULL,
reading numeric
) PARTITION BY RANGE (recorded_at);
CREATE TABLE measurements_2026_01 PARTITION OF measurements
FOR VALUES FROM ('2026-01-01') TO ('2026-02-01');
CREATE TABLE measurements_2026_02 PARTITION OF measurements
FOR VALUES FROM ('2026-02-01') TO ('2026-03-01');You insert into and query the parent. PostgreSQL routes each inserted row to the matching partition.
Bounds are inclusive at the bottom and exclusive at the top
FROM (a) TO (b) means a <= key < b. The lower bound belongs to the partition and the upper bound does not. This lets you chain partitions with no gaps. The upper bound of January is the lower bound of February, so a row stamped exactly 2026-02-01 00:00:00 goes to February.
Use this to avoid off-by-one mistakes. Never write the upper bound as "the last second of the month". A row at 2026-01-31 23:59:59.5 would then fit nowhere. Always use the first instant of the next period.
| Row value of `recorded_at` | Partition |
|---|---|
| `2026-01-31 23:59:59.999999+00` | `measurements_2026_01` |
| `2026-02-01 00:00:00+00` | `measurements_2026_02` |
| `2026-03-01 00:00:00+00` | no partition, error |
Overlaps and gaps
PostgreSQL refuses to create overlapping partitions:
CREATE TABLE measurements_bad PARTITION OF measurements
FOR VALUES FROM ('2026-01-15') TO ('2026-02-15');ERROR: partition "measurements_bad" would overlap partition "measurements_2026_01"Gaps are allowed, but they cause failures. A row whose key falls in a gap, or beyond the last partition, is rejected:
ERROR: no partition of relation "measurements" found for row
DETAIL: Partition key of the failing row contains (recorded_at) = (2026-03-15 00:00:00+00).There are two defences. You can create partitions ahead of time so the data never outruns them. You can also add a default partition to catch strays, which a later chapter covers.
If you insert directly into a partition with a value outside its range, PostgreSQL raises new row for relation "measurements_2026_01" violates partition constraint. Routing only happens through the parent.
Timestamps, time zones and date columns
For a date column, bounds are unambiguous. For timestamptz, a bare literal such as '2026-02-01' is interpreted in the session's TimeZone setting when you run the DDL. The stored bound is a fixed instant. A session in America/New_York therefore creates a partition boundary five hours later than one in UTC.
Write the offset explicitly so the result does not depend on who runs the script:
CREATE TABLE measurements_2026_04 PARTITION OF measurements
FOR VALUES FROM ('2026-04-01 00:00:00+00') TO ('2026-05-01 00:00:00+00');This matters for reporting. If your business months follow a local time zone, either choose bounds in that zone on purpose, or store UTC and group by month at query time. Decide this before creating the first partition. Changing boundaries later means moving data.
> Keep the choice of date, timestamp and timestamptz consistent between the key column and the literals in your queries. A mismatch can stop the planner from comparing values cleanly.
Reading what you created
Check where each row lives with tableoid:
INSERT INTO measurements (device_id, recorded_at, reading) VALUES
(1, '2026-01-10 08:00:00+00', 20.1),
(1, '2026-02-01 00:00:00+00', 19.4),
(2, '2026-02-14 12:30:00+00', 21.7);
SELECT tableoid::regclass AS partition, count(*)
FROM measurements
GROUP BY 1
ORDER BY 1; partition | count
-----------------------+-------
measurements_2026_01 | 1
measurements_2026_02 | 2The row stamped exactly 2026-02-01 00:00:00+00 appears in February, as the bound rules predict. psql's \d+ measurements also lists every partition with its bound expression.
Special bounds and multiple columns
Two keywords describe open-ended ranges. MINVALUE means "below every value" and MAXVALUE means "above every value". They let you cover everything without a default partition:
CREATE TABLE sales (
sold_on date NOT NULL,
amount numeric
) PARTITION BY RANGE (sold_on);
CREATE TABLE sales_before_2025 PARTITION OF sales
FOR VALUES FROM (MINVALUE) TO ('2025-01-01');
CREATE TABLE sales_2025 PARTITION OF sales
FOR VALUES FROM ('2025-01-01') TO ('2026-01-01');
CREATE TABLE sales_2026_onward PARTITION OF sales
FOR VALUES FROM ('2026-01-01') TO (MAXVALUE);Here every possible date has a home. The cost is that the last partition grows without limit, so you will eventually need to split it.
A range key can also have several columns, such as PARTITION BY RANGE (year, month). Bounds then compare as tuples, the way an ORDER BY year, month would. Each bound is a tuple, and the first column is compared first. This is easy to get wrong, and a single date or timestamptz column is almost always simpler.
The key can also be an expression, for example PARTITION BY RANGE ((recorded_at AT TIME ZONE 'UTC')). Queries must then filter on that same expression to benefit from pruning. Partitioning on the plain column is easier to keep correct.
Creating partitions ahead of time
Partitions are not created automatically by core PostgreSQL. A row for a month with no partition fails, so you need a routine that creates them in advance. Here is a script you can run from a scheduled job. It creates twelve monthly partitions starting in March 2026:
DO $$
DECLARE
start_day date := date '2026-03-01';
end_day date;
BEGIN
FOR i IN 1..12 LOOP
end_day := (start_day + interval '1 month')::date;
EXECUTE format(
'CREATE TABLE IF NOT EXISTS %I PARTITION OF measurements
FOR VALUES FROM (%L) TO (%L)',
'measurements_' || to_char(start_day, 'YYYY_MM'),
start_day::text || ' 00:00:00+00',
end_day::text || ' 00:00:00+00');
start_day := end_day;
END LOOP;
END
$$;It uses format with %I for identifiers and %L for literals, so names and values are quoted safely. IF NOT EXISTS makes the job safe to re-run. Extensions such as pg_partman do the same work with more features, but the underlying statements are these.
Choosing the interval size
Monthly partitions suit many workloads, but the right size depends on data volume and queries.
| Interval | Fits when | Risk |
|---|---|---|
| Daily | Very high write volume, retention in days | Hundreds of partitions per year, more planning work |
| Weekly | Moderate volume | Week boundaries do not match month reports |
| Monthly | Common default, retention in months or years | Large partitions if volume spikes |
| Yearly | Low volume, long retention | Little pruning benefit within a year |
Planning time grows with partition count, because the planner must consider each partition's bounds. A few dozen to a few hundred partitions is normal. Thousands usually call for coarser intervals. Aim for partitions that are large enough to matter and small enough that dropping one is a meaningful unit of work.
Common mistakes
- Using the upper bound as inclusive. Remember that
TOis exclusive. Chain partitions end to start. - Forgetting to create the next partition. Inserts start failing on the first day of the new period. Create partitions well ahead of time and monitor how many future ones remain.
- Bounds without a UTC offset on
timestamptz. Boundaries then shift with the session time zone. - Filtering on a different column than the key. A query on
device_idalone cannot skip any date partition, so it scans all of them. - Expecting a primary key on the date to be unique across the table. A unique constraint must include the partition key, which a later chapter covers.
Exercise
A table logs is partitioned by range on logged_at (type timestamptz). Partition logs_2026_05 was created FROM ('2026-05-01 00:00:00+00') TO ('2026-06-01 00:00:00+00'). In which partition does a row with logged_at = '2026-06-01 00:00:00+00' go, and what happens if no June partition exists?
Show answer
The upper bound is exclusive, so the row does not belong to logs_2026_05. It belongs in the June partition, which starts at that instant. If no June partition exists and there is no default partition, the insert fails with "no partition of relation "logs" found for row".
Exercise
Write the statement that adds a partition of measurements for March 2026 in UTC, and say why the offset is included in the bounds.
Show answer
CREATE TABLE measurements202603 PARTITION OF measurements FOR VALUES FROM ('2026-03-01 00:00:00+00') TO ('2026-04-01 00:00:00+00'); The offset is included because a timestamptz literal without one is read in the session's TimeZone, so the boundary would change depending on who runs the statement.