I have a table needs to be partitioned, but since the postgresql_partition_by
wasn’t added while the creation of the table so am trying to:
- create a new partitioned table that is similar the origin one.
- moving the data from the old one to the new one.
- drop the original one.
- rename the new one.
so what is the best-practice to move the data from the old table to the new one ??
I tried this and it didn’t work
COPY partitioned_table
FROM original_table;
also tried
INSERT INTO partitioned_table (column1, column2, ...)
SELECT column1, column2, ...
FROM original_table;
but both didn’t work 🙁
noting that I am using Alembic to generate the migration scripts also am using sqlalchemy from Python
2
Answers
After trying a few things, the solution was:
I don't know if there was an easier way to get the fields ordered, but I tried inserting a row in DBEver from these options:
Then got names like these steps:
Basically you have two scenarios described below.
– The table is large and you need to split the data in several partitions
– The table gets the first partition and you add new partition for new data
Lets use this setup for the not partitioned table
The table contains
id
from 1 to 1000 and for the first case you need to split them in two partition for 500 rows each.Create the partitioned table
with identical structure and constraints as the original table
Add partitions
to cover current data
for future data (as required)
Use insert to copy data
Note that this approach copy the data that means you need twice the space and a possible cleanup of the old data.
Check partition pruning
Note that only the partition
part_500
is accessedSecond Option – MOVE Data to one Partition
If you can live with the one (big) initial partition, you may use the second approach
Create the partitioned table
same as above
Attach the table as a partition
Now the original table gets the first partition of your partitioned table. I.e. no data duplication is performed.
Similar answer with some hints to automation of partition creation here