Question: How do you remove partitioning from a PostgreSQL table?

Answer

Removing partitioning from a PostgreSQL table involves detaching or deleting the partitions and then optionally converting the partitioned table into a regular table. This can be especially useful when the partitioning strategy no longer serves its intended purpose, or if simplifying the table structure is desired for performance tuning or maintenance purposes.

Step 1: Detach Partitions

If you wish to keep the data in the partitions but remove the partitioning structure, you first need to DETACH each partition. This makes the partition a separate, standalone table.

ALTER TABLE parent_table DETACH PARTITION partition_name;

Repeat this command for each partition that you want to detach. After detaching, the tables will still exist but will no longer be connected as part of a partitioned table structure.

Step 2: Drop Partitioned Table (Optional)

If you don’t need the empty partitioned table anymore, you can drop it after detaching all partitions:

DROP TABLE IF EXISTS parent_table;

This step is optional and should be executed only if you’re sure that the partitioned table's structure, without any partitions attached, is no longer needed.

Step 3: Convert Detached Partitions into Regular Tables (Already Done)

By the act of detaching, the partitions become regular tables automatically. Therefore, there is no additional action required to ""convert"" them. However, you might want to consider reindexing or vacuuming these newly independent tables to optimize their performance:

VACUUM (ANALYZE) detached_table_name; REINDEX TABLE detached_table_name;

Considerations

  • Data Consistency: Ensure that the application layer or any database queries are adjusted accordingly to account for the change in table structures.
  • Backup: Always take a backup before performing structural changes to your database.
  • Foreign Keys & Indexes: When detaching partitions, remember to recreate any necessary foreign keys or indexes on the now-detached tables to maintain referential integrity and performance.

Removing partitioning can help simplify your database schema or adapt it to changing requirements. Carefully planning and executing the above steps can ensure a smooth transition away from a partitioned table setup.

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.