DISCLAIMER: This question is similar to the stack overflow question here, but none of those answers work for my problem, as I will explain later.
I'm trying to copy a large table (~40M rows, 100+ columns) in postgres where a lot of the columns are indexed. Currently I use this bit of SQL:
CREATE TABLE <tablename>_copy (LIKE <tablename> INCLUDING ALL);
INSERT INTO <tablename>_copy SELECT * FROM <tablename>;
This method has two issues:
The table size makes indexing a real time issue. It also makes it infeasible to dump to a file to then re-ingest. I also don't have the advantage of a command line. I need to do this in SQL.
What I'd like to do is either straight make an exact copy with some miracle command, or if that's not possible, to copy the table with all contraints but without indices, and make sure they're the constraints 'in spirit' (aka a new counter for a SERIAL column). Then copy all of the data with a SELECT *
and then copy over all of the indices.
Sources
Stack Overflow question about database copying: This isn't what I'm asking for for three reasons
pg_dump -t x2 | sed 's/x2/x3/g' | psql
and in this setting I don't have access to the command linedefault nextval('x1_id_seq'::regclass)
Method to reset the sequence value for a postgres table: This is great, but unfortunately it is very manual.
The create table as
feature in PostgreSQL may now be the answer the OP was looking for.
https://www.postgresql.org/docs/9.5/static/sql-createtableas.html
create table my_table_copy as
select * from my_table
This will create an identical table with the data.
Adding with no data
will copy the schema without the data.
create table my_table_copy as
select * from my_table
with no data
This will create the table with all the data, but without indexes and triggers etc.
create table my_table_copy (like my_table including all)
The create table like syntax will include all triggers, indexes, constraints, etc. But not include data.