How do you use the ALTER TABLE statement to switch partitions in a partitioned table?
Posted by FrankMl
Last Updated: June 26, 2024
In SQL databases that support partitioning (such as PostgreSQL, MySQL, Oracle, and SQL Server), the ALTER TABLE statement can be used to manage partitions. The exact syntax and functionality may vary between different database systems, but I’ll provide a general overview and examples for some popular databases.
1. PostgreSQL
In PostgreSQL, you can use the ALTER TABLE command along with the DETACH PARTITION or ATTACH PARTITION statements to switch or manage partitions.
Example:
-- Detach a partition
ALTER TABLE my_partitioned_table DETACH PARTITION my_partition;

-- Attach a new partition
ALTER TABLE my_partitioned_table ATTACH PARTITION new_partition FOR VALUES BETWEEN (start_value) AND (end_value);
2. MySQL
In MySQL, you can manage partitions with the ALTER TABLE statement to exchange partitions accordingly.
Example:
-- Exchange partitions
ALTER TABLE my_partitioned_table 
EXCHANGE PARTITION partition_name 
WITH TABLE table_name;
With this, all data in partition_name will be swapped with table_name.
3. Oracle
In Oracle, to exchange a partition with a table, you would use the following:
Example:
ALTER TABLE my_partitioned_table
EXCHANGE PARTITION partition_name WITH TABLE table_name;
This command exchanges the specified partition with the data in the specified table.
4. SQL Server
In SQL Server, you can use partition switching but it involves a bit more setup like defining a partition function, and performing management using the SWITCH command.
Example:
-- Example setup (for context)
-- Assuming you have partitioned a table already set up with a partition scheme

-- Switch partitions
ALTER TABLE my_partitioned_table
SWITCH TO my_table_name PARTITION partition_number;
General Notes:
- Always ensure that the data types of the tables/partitions match. - For many of these commands, the table you are exchanging with should be non-partitioned or an empty table with the same structure as the partition being exchanged. - It's crucial to refer to the documentation specific to the database system you are using, as syntax and options might change between versions. Make sure to test your operations in a development environment before executing them on a production database to avoid data loss and ensure consistency.
Related Content