Copy table structure into new table

前端 未结 5 547
予麋鹿
予麋鹿 2020-12-07 14:30

Is there a way to copy the structure of a table into a new table, without data, including all keys and constraints?

相关标签:
5条回答
  • 2020-12-07 14:35

    To copy a table completely, the short form using the TABLE command can also be used:

    CREATE TABLE films2 AS
        TABLE films
        WITH NO DATA;
    

    More details here

    0 讨论(0)
  • 2020-12-07 14:35

    How about

    CREATE TABLE sample_table_copy AS (SELECT * FROM sample_table WHERE 1 = 2)
    

    postgresql.org answer

    0 讨论(0)
  • 2020-12-07 14:42

    Well, the closest you can get with SQL is:

    create table new (
        like old
        including defaults
        including constraints
        including indexes
    );
    

    But it will not copy everything. The most important things that are missing are FOREIGN KEYs. Also - triggers are also not copied. Not sure about other things.

    Another way is to dump the table structure, change it's name in dump, and load it again:

    pg_dump -s -t old databases | sed 's/old/new/g' | psql
    

    But beware, that such simplistic sed will also change old to new in other places (for example if you have in your table column named "is_scolded" it will become "is_scnewed").

    The question really is rather: why do you need it - because for various purposes, I would use different techniques.

    0 讨论(0)
  • 2020-12-07 14:47

    For a simple schema copy use the like clause.

    CREATE TABLE new_table_name ( like old_table_name including all)
    
    0 讨论(0)
  • 2020-12-07 14:49

    Take a look at pgAdmin - by far the easiest way to do what you want.
    Right-click on table, Scripts - Create.

    0 讨论(0)
提交回复
热议问题