5

I know that I could do CREATE TABLE tbl_2 AS (select * from tbl_1)

But is there a better/faster/stronger way to do this? I am talking about performance more than anything else. The tables are all denormalised and I do not have any foreign key constraints to worry about.

EDIT

May be there isn't any better way? Ref: https://dba.stackexchange.com/questions/55661/how-to-duplicate-huge-postgres-table

1
  • create table as ... select ... is as fast as it gets. Btw: the parentheses around the select are totally useless. Commented Aug 31, 2016 at 5:52

2 Answers 2

4

A better way really depends on what exactly you're hoping to accomplish.

If you want to keep all the constraints and indexes from the original table you can use the LIKE clause in your CREATE TABLE statement like so:

CREATE TABLE tbl_2 (LIKE tbl_1 INCLUDING INDEXES INCLUDING CONSTRAINTS);

But that just creates an empty table. You would still have to copy in the data.

Sign up to request clarification or add additional context in comments.

1 Comment

I am hoping to have the fastest in terms of performance. Also not really bothered about the constraints here because my use case does not demand it.
0

Alternatively you can use something like the following:

$ pg_dump -t tbl_1 | sed -e 's/^SET search_path = .*$/SET search_path = tmpschema, pg_catalog;' > table.sql
$ psql -d test -c 'CREATE SCHEMA tmpschema'
$ psql -1 -d test -f table.sql
$ psql -d test -c 'ALTER TABLE tmpschema.tbl_1 RENAME TO tbl_2; ALTER TABLE tmpschema.tbl_2 SET SCHEMA public; DROP SCHEMA tmpschema'

Perhaps it is not faster than CREATE TABLE ... AS (SELECT ...), but it will copy all indexes and constraints as well.

2 Comments

The LIKE clause in a create table statement can create a new table with the same indexes and constraints a bit more easily than using pg_dump.
Right, but it does not copy the table contents. You could run CREATE TABLE ... LIKE ... and then INSERT INTO ... (SELECT ...), but that would certainly be slow, because the indexes and constraints are already defined. pg_dump dumps the indexes and constraints after the table data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.