How to migrate from inheritance-based partitioning to declarative partitioning in PostgreSQL?

Declarative partitioning is a feature in PostgreSQL that allows you to define partitions for a table in a declarative manner, without having to use inheritance. With declarative partitioning, you can define partitioning rules using the CREATE TABLE statement, and PostgreSQL will automatically create and manage the partitions for you.

In PostgreSQL, migrating from inheritance-based partitioning to declarative partitioning can be done in the following steps:

  1. Create a new parent table for declarative partitioning: Use the CREATE TABLE statement to create a new parent table for declarative partitioning. This table should have the same columns as the existing parent table, but without any constraints or triggers.
  2. Create child tables for each partition: Use the CREATE TABLE statement to create child tables for each partition. These tables should have the same columns as the existing child tables, but with constraints and triggers that define the partitioning rules.
  3. Populate the new child tables: Use the INSERT INTO statement to populate the new child tables with data from the existing child tables. This can be done in batches to avoid locking the tables for an extended period of time.
  4. Modify foreign keys and indexes: Update any foreign keys and indexes that reference the existing child tables to reference the new child tables.
  5. Test the new partitioning setup: Verify that the new partitioning setup works as expected by running queries and comparing the results to the old partitioning setup.
  6. Drop the old child tables: Once you are satisfied that the new partitioning setup works correctly, you can drop the old child tables.
  7. Modify application code: Update any application code that references the old child tables to reference the new child tables instead.

Note that migrating from inheritance-based partitioning to declarative partitioning can be a complex process, especially if the existing partitioning setup is highly customized. It is recommended to perform the migration in a test environment first to ensure that the new partitioning setup works correctly before making the changes in production.

About Shiv Iyer 446 Articles
Open Source Database Systems Engineer with a deep understanding of Optimizer Internals, Performance Engineering, Scalability and Data SRE. Shiv currently is the Founder, Investor, Board Member and CEO of multiple Database Systems Infrastructure Operations companies in the Transaction Processing Computing and ColumnStores ecosystem. He is also a frequent speaker in open source software conferences globally.