Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

PostgreSQL Horizontal Partitioning: How It Organizes Table Rows

· 6 min read · Home Tech

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

Horizontal partitioning in PostgreSQL splits a large table into smaller, more manageable pieces called partitions, while keeping them accessible as a single logical table. This improves query performance, simplifies data archival, and speeds up bulk deletes. Before you begin, ensure you have PostgreSQL 10 or later (which introduced declarative partitioning) and appropriate permissions to create tables and indexes.

What You'll Need

  • PostgreSQL 10 or newer (declarative partitioning is not available in earlier versions).
  • Access to a database where you can create tables (e.g., a superuser or a role with CREATE privileges).
  • A clear partitioning key—usually a date column or an ID—that determines which partition each row belongs to.
  • Basic familiarity with SQL commands like CREATE TABLE, INSERT, and SELECT.

Step-by-Step

  1. Choose your partitioning strategy. The most common is range partitioning (e.g., by date or numeric range). List partitioning (by discrete values like region) and hash partitioning (by a hash of a column) are also available. For this guide, we'll use range partitioning on a date column.
  2. Create the parent table. Define the table structure and specify the partition key in the PARTITION BY clause. For example:
    CREATE TABLE sales (
        id SERIAL,
        sale_date DATE NOT NULL,
        amount NUMERIC
    ) PARTITION BY RANGE (sale_date);
    This creates a partitioned table named sales that will have partitions based on the sale_date column.
  3. Create the individual partitions. Each partition is a separate table that inherits the parent's structure. For range partitioning, you define a minimum and maximum bound using FROM and TO. For example:
    CREATE TABLE sales_2024_q1 PARTITION OF sales
        FOR VALUES FROM ('2024-01-01') TO ('2024-04-01');
    This creates a partition for all rows with sale_date from January 1, 2024 (inclusive) to April 1, 2024 (exclusive). Create as many partitions as you need to cover your data range.
  4. Create indexes on each partition. Indexes are created per partition, not on the parent. You can create them manually, or use the CREATE INDEX ON ONLY syntax to create an index on the parent that will automatically apply to future partitions. For existing partitions, create indexes directly:
    CREATE INDEX idx_sales_2024_q1_date ON sales_2024_q1 (sale_date);
    For future partitions, you can create a default index on the parent that will be inherited:
    CREATE INDEX ON ONLY sales (sale_date);
    Then attach it to existing partitions with ALTER INDEX ... ATTACH PARTITION.
  5. Insert data normally. When you insert a row into the parent table, PostgreSQL automatically routes it to the correct partition based on the partition key. For example:
    INSERT INTO sales (sale_date, amount) VALUES ('2024-02-15', 100);
    This row will go into sales_2024_q1 automatically.
  6. Query the parent table. You can query the parent table as if it were a regular table. PostgreSQL will only scan the relevant partitions, a process called partition pruning. For example:
    SELECT * FROM sales WHERE sale_date BETWEEN '2024-01-01' AND '2024-03-31';
    This will only scan sales_2024_q1.
  7. Manage partitions over time. As new data arrives, create new partitions before the old ones fill up. You can also detach or drop old partitions to archive or delete data quickly. For example, to drop an old partition:
    DROP TABLE sales_2023_q4;
    This is much faster than a DELETE on a large table.

Common Mistakes

  • Forgetting the partition key in WHERE clauses. If you query without filtering on the partition key, PostgreSQL must scan all partitions, negating the performance benefit.
  • Creating partitions that overlap. Range partitions must not overlap. Ensure each partition's TO bound matches the next partition's FROM bound.
  • Not creating indexes on partitions. Indexes are per-partition; if you only index the parent, existing partitions won't have indexes.
  • Using a non-immutable partition key expression. The partition key must be a column or an expression that is immutable (does not change over time). For example, using now() directly is not allowed.
  • Forgetting to handle default partitions. If you don't create a default partition, any row that doesn't match an existing partition will cause an error on insert. Consider creating a default partition for out-of-range data.

Tips

  • Plan your partition boundaries ahead. For date-based partitioning, decide on the granularity (daily, monthly, yearly) based on your data volume and query patterns.
  • Use a naming convention. Name partitions clearly, e.g., sales_2024_01, to make management easier.
  • Automate partition creation. Use a scheduled job (e.g., pg_cron) to create new partitions before the current one fills up.
  • Consider using a default partition. This catches any rows that don't fit existing partitions, preventing insert errors. You can later move them to the correct partition if needed.
  • Test with a small dataset. Before applying partitioning to a production table, test the schema and queries on a development server.
  • Monitor partition sizes. Use queries against pg_partition_tree to see how many rows are in each partition and identify any that are growing unexpectedly.

Troubleshooting

  • Insert fails with "no partition of relation found for row". This means the row's partition key value doesn't fall into any existing partition. Create a new partition that covers that value, or add a default partition.
  • Queries are slow even with partitioning. Check if the query planner is actually pruning partitions. Use EXPLAIN to see which partitions are scanned. If all are scanned, ensure the WHERE clause uses the partition key with a constant or a parameter, not a function that prevents pruning.
  • Indexes are not being used. Verify that indexes exist on each partition. If you created an index on the parent only, it won't apply to existing partitions until you attach them. Use \d+ partition_name to inspect indexes.
  • Cannot drop a partition because of foreign key constraints. If other tables reference the partition, you need to drop or alter those constraints first, or use ALTER TABLE ... DETACH PARTITION to remove it without deleting data.
  • Partition key column is updated. If you update a row's partition key so it no longer belongs to its current partition, PostgreSQL will move the row to the correct partition automatically (since version 11). If it fails, check that the target partition exists.

Frequently Asked Questions

Can I partition an existing table?

Yes, but you cannot directly convert a normal table to a partitioned one. You must create a new partitioned table, copy data over, then rename and drop the old table. Use INSERT INTO partitioned_table SELECT * FROM old_table; to move data.

What is the difference between partitioning and sharding?

Partitioning splits a table within the same database server, while sharding distributes data across multiple servers. Partitioning is easier to manage and is built into PostgreSQL; sharding requires external tools or extensions.

Can I have a primary key on a partitioned table?

Yes, but the primary key must include the partition key column. This is because each partition is a separate table, and PostgreSQL cannot enforce uniqueness across partitions without including the partition key in the constraint.

How do I know which partition a row belongs to?

You can use the tableoid system column, which returns the OID of the table that actually stores the row. Join with pg_class to get the partition name.

Can I use foreign keys on a partitioned table?

Yes, you can define foreign keys from a partitioned table to another table. However, foreign keys referencing a partitioned table are not supported—you must reference the parent table, and PostgreSQL will handle the routing.

Does partitioning improve performance for all queries?

No. Partitioning mainly helps queries that filter on the partition key, allowing partition pruning. Queries that scan the entire table or filter on non-partition columns may see a slight overhead due to multiple table scans.