Question: How do you add a column to a partitioned table in PostgreSQL?

Answer

Adding a column to a partitioned table in PostgreSQL is largely similar to adding a column to any regular table. The main difference lies in how these changes propagate to the table's partitions. In PostgreSQL, when you add a column to a parent table, this change automatically applies to all its child partitions.

Here's a step-by-step guide to adding a column to a partitioned table:

  1. Determine the Partitioned Table: First, identify the partitioned table to which you want to add a column. For demonstration, let's say the partitioned table's name is sales_data.

  2. Add the Column: Use the ALTER TABLE command to add a new column to the partitioned table. PostgreSQL will automatically update all existing partitions with this new column. Suppose you want to add a comments column of type TEXT to the sales_data table:

ALTER TABLE sales_data ADD COLUMN comments TEXT;

After executing this command, the comments column will be present in the sales_data table and all its partitions.

  1. Verify the Change: To ensure that the column has been added to both the partitioned table and its partitions, you can inspect the table structure using the \d+ command in the psql terminal or query the information_schema.columns table:
SELECT table_name, column_name FROM information_schema.columns WHERE table_name IN ('sales_data', 'partition_1', 'partition_2') AND column_name = 'comments';

Replace 'partition_1', 'partition_2' with your actual partition names. The output should confirm the presence of the comments column in the specified tables.

Best Practices

  • Consider Locking: Altering a table to add a column requires an ACCESS EXCLUSIVE lock on the table for the duration of the operation. While this process is generally fast, it can block other operations on the table. Plan to make such changes during low-traffic periods if possible.

  • Default Values and NOT NULL Constraints: If you're adding a column with a default value or a NOT NULL constraint, PostgreSQL needs to rewrite the entire table and all its partitions. This process can take a significant amount of time and disk space for large tables. Evaluate the impact before proceeding with such alterations.

In summary, adding a column to a partitioned table in PostgreSQL is straightforward and propagates to all partitions automatically. However, consider the operational implications, especially when dealing with large datasets or constraints that require table rewrites.

Was this content helpful?

White Paper

Free System Design on AWS E-Book

Download this early release of O'Reilly's latest cloud infrastructure e-book: System Design on AWS.

Free System Design on AWS E-Book
Start building today

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.