TechBuzzPro

PostgreSQL Partition Table: Step-by-Step Guide

· 5 min read · Apps & Browsers

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Partitioning in PostgreSQL splits a large table into smaller, more manageable pieces called partitions, while still querying it as a single table. This improves query performance, speeds up data deletion (by dropping whole partitions), and simplifies maintenance. This guide walks you through creating a partitioned table using declarative partitioning (introduced in PostgreSQL 10), covering range, list, and hash methods.

What You'll Need

  • A PostgreSQL instance (version 10 or later) with sufficient privileges to create tables (usually the table owner or a superuser).
  • Access to a SQL client (psql, pgAdmin, DBeaver, etc.)
  • A clear idea of the partitioning key (the column you'll partition by) and the partition strategy (range, list, or hash).

Step-by-Step

  1. Decide on the partitioning strategy.
    • Range: Partition by a date or numeric range (e.g., monthly sales).
    • List: Partition by discrete values (e.g., region names).
    • Hash: Distribute data evenly across a fixed number of partitions (useful when no natural range/list exists).
  2. Create the parent (partitioned) table. Use the PARTITION BY clause. For example, a range-partitioned table on a sale_date column:
    CREATE TABLE sales (
        id serial,
        sale_date date NOT NULL,
        amount numeric
    ) PARTITION BY RANGE (sale_date);
    For list: PARTITION BY LIST (region). For hash: PARTITION BY HASH (customer_id).
  3. Create the individual partitions. Each partition is a regular table that inherits the parent's structure. You must define the partition bounds. For range:
    CREATE TABLE sales_2024_q1 PARTITION OF sales
        FOR VALUES FROM ('2024-01-01') TO ('2024-04-01');
    For list:
    CREATE TABLE sales_europe PARTITION OF sales
        FOR VALUES IN ('UK', 'FR', 'DE');
    For hash, specify the modulus and remainder:
    CREATE TABLE sales_hash_0 PARTITION OF sales
        FOR VALUES WITH (MODULUS 4, REMAINDER 0);
    Repeat for each partition you need. Ensure the ranges do not overlap and cover all possible values (or add a default partition).
  4. Add indexes and constraints to each partition. Indexes are not automatically created on partitions. You can create them individually, or create an index on the parent table, which PostgreSQL will automatically propagate to all existing and future partitions:
    CREATE INDEX idx_sales_date ON sales (sale_date);
    For a composite index, create it on the parent as well.
  5. Enable row-level security or other table features if needed. These are applied per partition, so you may need to set them on each partition or use the parent's defaults.
  6. Insert data. Insert into the parent table; PostgreSQL automatically routes rows to the correct partition based on the partition key. If no matching partition exists and no default partition is defined, the insert will error.
  7. Query the parent table. Queries against the parent automatically scan only relevant partitions (partition pruning), so you don't need to query partitions directly.
  8. Manage partitions over time. For range partitions, you'll typically create new partitions ahead of time (e.g., monthly) and drop old ones:
    CREATE TABLE sales_2024_q2 PARTITION OF sales
        FOR VALUES FROM ('2024-04-01') TO ('2024-07-01');
    
    DROP TABLE sales_2023_q1;
    Dropping a partition is quick because it just drops a table.

Common Mistakes

  • Overlapping ranges: If two range partitions overlap, inserts may fail or route to the wrong partition. Always check boundaries.
  • Missing default partition: Without a default partition, any row that doesn't match a partition's bounds causes an error. Add a default if you expect unexpected values.
  • Forgetting indexes on partitions: Indexes created directly on partitions are not automatically added to future partitions; create them on the parent instead.
  • Using non-immutable functions in partition key expressions: Partition key must be a column or an expression using immutable functions. Using now() directly is not allowed; use a generated column or a trigger.
  • Not updating the default partition when adding new partitions: If you have a default partition, new range partitions must be created before data arrives; otherwise rows go to the default and are not pruned efficiently.
  • Assuming all queries get faster: Partitioning helps only when queries filter on the partition key. Queries that don't filter on it will scan all partitions, which can be slower than a single table.

Tips

  • Use pg_partman extension for automated partition creation and maintenance, especially for time-based partitions.
  • For range partitions, choose a range size that balances partition count and row count per partition. Too many small partitions can slow down queries.
  • Always create a default partition as a safety net, but monitor it—rows landing there often indicate a missing range.
  • Use EXPLAIN to verify that partition pruning is working: look for “Seq Scan on sales_2024_q1” instead of “Append” scanning all partitions.
  • When attaching a large existing table as a partition, use ATTACH PARTITION with VALIDATE CONSTRAINT to avoid long locks.
  • Consider using generated columns for partition keys based on expressions, e.g., sale_month date GENERATED ALWAYS AS (date_trunc('month', sale_date)) STORED.

Troubleshooting

  • Insert fails with “no partition of relation found for row”: Add a partition that covers the value, or add a default partition. Check the data type and bounds.
  • Queries are slow and scan all partitions: Ensure the WHERE clause uses the partition key. Check EXPLAIN; if you see “Append” with all partitions, the query isn't pruning.
  • Cannot create index on parent: Make sure you're using PostgreSQL 11 or later; earlier versions required indexes on each partition individually.
  • Partition key column cannot be altered: You cannot change the partition key of an existing partitioned table. You must recreate it.
  • Error: “cannot create a partition of relation with non-immutable function in partition key”: Use a generated column or a trigger to compute the partition key.
  • Partition table is larger than expected: Check if rows are going to the default partition due to gaps in ranges. Query the default partition to inspect.

Frequently Asked Questions

Can I partition an existing table without losing data?

Yes, but it requires creating a new partitioned table, copying data, then renaming. Use CREATE TABLE ... (LIKE ...) and INSERT INTO ... SELECT, or use pg_partman to automate.

What is the difference between partitioning and inheritance?

Declarative partitioning (this guide) is built into PostgreSQL and automatically handles routing and pruning. Traditional inheritance requires triggers and manual management.

Can I have foreign keys on a partitioned table?

Yes, a partitioned table can be a parent in a foreign key, but referencing a partitioned table as the child is not supported directly. You'd need to create foreign keys on each partition.

How many partitions should I create?

There's no fixed number. Keep it manageable—hundreds are fine, but thousands may degrade performance. Start with a range that matches your data growth (e.g., monthly) and adjust.

Does partitioning automatically delete old data?

No, but you can drop old partitions manually or via a scheduled job. Dropping a partition is much faster than deleting rows.

Can I use partitioning with foreign data wrappers?

Yes, you can create partitions that are foreign tables, but routing and pruning may have limitations depending on the FDW.