PostgreSQL

PostgreSQL Declarative Partitioning for Time-Series Tables

Append-heavy tables such as audit_logs, events or sensor_readings tend to grow without limit. Past a certain size, routine work gets painful: autovacuum takes hours, deleting old rows generates huge amounts of WAL, and indexes outgrow memory. PostgreSQL's declarative partitioning splits one logical table into smaller physical tables, so queries can skip irrelevant data and old data can be dropped as a whole partition instead of deleted row by row.

This guide sets up range partitioning for a sensor_readings table and covers the parts that matter in production: the primary key rule, partition pruning, migrating existing data, and automating partition creation and removal. Examples assume PostgreSQL 14 or later.

The Scaling Headache: Why Large Tables Become a Bottleneck

Before diving into the solution, it's crucial to understand the problems large tables introduce.

Performance Degradation

When a table grows excessively large, several performance bottlenecks emerge:

  • Index Bloat and Inefficiency: Indexes, though critical, become massive themselves. Scanning these larger indexes takes more I/O, and the sheer number of entries can make them less effective, requiring more memory and CPU for lookups.
  • Cache Invalidation: As more data is accessed, fewer 'hot' pages can reside in memory. This leads to more disk reads, which are orders of magnitude slower than memory reads.
  • Slower Sequential Scans: While indexes help with specific lookups, many analytical or batch queries still rely on scanning large portions of the table. A larger table means longer scans.
  • Vacuum Overhead: PostgreSQL's MVCC (Multi-Version Concurrency Control) relies on VACUUM to clean up dead tuples. A plain VACUUM doesn't block reads or writes, but on a very large table it can run for hours, compete for I/O, and fall behind, which leads to bloat and, in the worst case, transaction ID wraparound pressure.

Maintenance Challenges

Beyond query performance, large tables pose significant operational challenges:

  • Backup and Restore Times: Backing up and restoring multi-terabyte tables can take hours, which makes restore-time targets hard to meet.
  • Schema Migrations: Adding or modifying columns on a table with billions of rows can result in prolonged lock times, potentially leading to unacceptable downtime.
  • Data Archiving/Deletion: Removing old data often involves DELETE statements that can lock the table for extended periods, or generate massive amounts of WAL (Write-Ahead Log) activity, straining storage and replication.

How Declarative Partitioning Works

PostgreSQL has supported declarative partitioning since version 10, and versions 11–14 fixed most of its early limitations (default partitions, parent-level indexes, faster pruning, DETACH ... CONCURRENTLY). It allows you to logically divide a single large table (the parent table) into smaller, more manageable physical tables (the child partitions or partitions). From an application perspective, you interact only with the parent table, and PostgreSQL automatically routes queries and data inserts to the correct child partition.

How It Works and Its Benefits

Declarative partitioning supports three strategies:

  • RANGE Partitioning: Partitions are defined by ranges of values (e.g., timestamps, IDs). Ideal for time-series data or sequential IDs.
  • LIST Partitioning: Partitions are defined by specific values (e.g., country codes, department IDs). Useful for categorizing data.
  • HASH Partitioning: Partitions are defined by a hash value of a column, distributing data evenly across partitions. Good for balancing load across many small partitions.

For our sensor_readings example, RANGE partitioning by timestamp is the most natural fit. The benefits are substantial:

  • Improved Query Performance: Queries often only need to scan a subset of partitions, reducing the amount of data read. PostgreSQL's partition pruning automatically excludes irrelevant partitions.
  • Faster Maintenance Operations: Autovacuum and ANALYZE work partition by partition, and old partitions are rarely modified, so they need little vacuuming. Removing a month of data becomes DROP TABLE on one partition instead of a huge DELETE.
  • Reduced Index Sizes: Each partition has its own indexes, which are much smaller and more efficient than a single monolithic index on the parent table.
  • Partition-wise operations: With enable_partitionwise_join and enable_partitionwise_aggregate (both off by default), the planner can join or aggregate partition by partition, which helps some analytical queries.

Partitioning isn't free. Queries that don't filter on the partition key have to visit every partition, and planning time grows with the number of partitions. Keep the count in the hundreds, not tens of thousands.

Step-by-Step Setup

Let's walk through implementing RANGE partitioning for a sensor_readings table.

Step 1: Identify Your Partition Key

The partition key is the column (or set of columns) that determines which partition a row belongs to. For time-series data, a timestamp or date column is usually the best choice. Every primary key and unique constraint on a partitioned table must include the partition key, because PostgreSQL enforces uniqueness separately within each partition.

For our sensor_readings table, recorded_at will be our partition key.

Step 2: Create the Parent Partitioned Table

This table will serve as the logical entry point. It has no actual storage itself; it merely defines the schema and the partitioning strategy.

SQL
CREATE TABLE sensor_readings (
    id BIGSERIAL NOT NULL,
    sensor_id INT NOT NULL,
    temperature DECIMAL(5, 2) NOT NULL,
    humidity DECIMAL(5, 2) NOT NULL,
    recorded_at TIMESTAMP WITH TIME ZONE NOT NULL,
    PRIMARY KEY (id, recorded_at) -- Partition key must be part of the PK
) PARTITION BY RANGE (recorded_at);

-- Add an index on sensor_id for common queries, applied to the parent table
-- This index will automatically be created on child partitions as well.
CREATE INDEX idx_sensor_readings_sensor_id ON sensor_readings (sensor_id);

Notice PARTITION BY RANGE (recorded_at). This tells PostgreSQL how to divide the data. Also, the PRIMARY KEY must include the partition key recorded_at.

Step 3: Create the Child Partitions

Now, we create the actual storage tables, linking them to the parent. It's common practice to create partitions covering specific time periods (e.g., months, weeks, days).

Let's create partitions for January, February, and March 2024.

SQL
CREATE TABLE sensor_readings_2024_01
PARTITION OF sensor_readings FOR VALUES FROM ('2024-01-01 00:00:00+00') TO ('2024-02-01 00:00:00+00');

CREATE TABLE sensor_readings_2024_02
PARTITION OF sensor_readings FOR VALUES FROM ('2024-02-01 00:00:00+00') TO ('2024-03-01 00:00:00+00');

CREATE TABLE sensor_readings_2024_03
PARTITION OF sensor_readings FOR VALUES FROM ('2024-03-01 00:00:00+00') TO ('2024-04-01 00:00:00+00');

-- You can also create a 'future' partition or a default partition for unforeseen data.
-- For a default partition (handles all values not covered by other partitions):
-- CREATE TABLE sensor_readings_default PARTITION OF sensor_readings DEFAULT;

When inserting data into sensor_readings, PostgreSQL will automatically route it to the correct child table based on the recorded_at value. If no suitable partition exists, the insert will fail (unless a DEFAULT partition is defined).

Step 4: Migrate Existing Data (If Applicable)

If you're partitioning an existing table, you have to move its data, since an existing table can't be converted into a partitioned one in place. For small and medium tables, copy the data into the new structure in batches and then swap table names in a short transaction. For very large tables, a common approach is to rename the old table and ATTACH it as one big "historical" partition, so only new data lands in the new monthly partitions.

SQL
-- Copy one month at a time to keep transactions and WAL bursts small
INSERT INTO sensor_readings (id, sensor_id, temperature, humidity, recorded_at)
SELECT id, sensor_id, temperature, humidity, recorded_at
FROM old_sensor_readings
WHERE recorded_at >= '2024-01-01' AND recorded_at < '2024-02-01';

-- After copying, move the sequence past the highest copied id
SELECT setval(pg_get_serial_sequence('sensor_readings', 'id'),
              (SELECT max(id) FROM sensor_readings));

Step 5: Understand How Indexes Propagate

Since PostgreSQL 11, an index created on the parent partitioned table is automatically created on every existing partition and on any partition added later. Before version 11, you had to create indexes on each partition by hand.

When you ATTACH an existing table as a partition, PostgreSQL reuses any matching index it already has and builds the missing ones, which can take a long time on a big table. It also scans the table to check that every row fits the partition bounds, while holding a lock on it. To skip that scan, add a CHECK constraint matching the bounds beforehand (it can be added NOT VALID and validated separately without blocking writes).

⚠️ Common mistake: Writing queries that hide the partition key from the planner, such as WHERE date(recorded_at) = '2024-02-10' or WHERE recorded_at::date = .... Wrapping the column in a function prevents partition pruning, so every partition gets scanned. Use a range instead: WHERE recorded_at >= '2024-02-10' AND recorded_at < '2024-02-11'.

Step 6: Automate Partition Management

Manually creating partitions is not sustainable in production. You'll need a mechanism to automatically create new partitions ahead of time (e.g., monthly) and potentially detach old ones for archiving. This can be done via:

  • pg_partman: The most widely used extension for this. It pre-creates future partitions and applies a retention policy from a background worker or a scheduled call.
  • A scheduled job of your own: A cron job or pg_cron task that creates partitions a few periods ahead, for example:
SQL
-- Create next month's partition if it doesn't exist yet
DO $$
DECLARE
    start_date date := date_trunc('month', now() + interval '1 month');
    end_date   date := start_date + interval '1 month';
    part_name  text := 'sensor_readings_' || to_char(start_date, 'YYYY_MM');
BEGIN
    EXECUTE format(
        'CREATE TABLE IF NOT EXISTS %I PARTITION OF sensor_readings
         FOR VALUES FROM (%L) TO (%L)', part_name, start_date, end_date);
END $$;

Create partitions well ahead of time (at least one period). If an insert arrives for a range with no partition and there's no default partition, it fails.

Beyond the Basics: Advanced Considerations

  • DEFAULT partition: A default partition catches rows outside every defined range, which prevents failed inserts. The catch: when you later create a partition, PostgreSQL has to scan the default partition to make sure none of its rows belong in the new range. Keep the default partition empty and monitor it.
  • Removing old data: ALTER TABLE sensor_readings DETACH PARTITION sensor_readings_2023_01 CONCURRENTLY; (PostgreSQL 14+) detaches without blocking queries on the parent. After that you can archive it (for example with pg_dump -t) and DROP it. Without CONCURRENTLY, DETACH takes an ACCESS EXCLUSIVE lock on the parent table.
  • Verify pruning: Run EXPLAIN on your common queries and check which partitions appear in the plan. A query filtered to one month should list one partition, not all of them. With prepared statements or parameters, pruning can happen at execution time and shows up in EXPLAIN ANALYZE as "Subplans Removed".

Summary

  1. Partition when the table's lifecycle hurts, not just its size: Time-series tables where you query recent data and drop old data are the best fit.
  2. Include the partition key in every primary key and unique constraint, and choose the key your queries actually filter on.
  3. Create indexes on the parent table so they propagate to every partition, including future ones.
  4. Automate partition creation and retention with pg_partman or a scheduled job, and create partitions ahead of time.
  5. Check EXPLAIN output to confirm pruning, and avoid wrapping the partition key in functions inside WHERE clauses.

For finding which queries are slow in the first place, see our guide on reading EXPLAIN ANALYZE output.

Advertisement