Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy table structure into new table

Tags:

sql

postgresql

People also ask

How do you copy the structure of a existing table student to new table new student?

To export data to an existing table you can use insert command. This will create a new table student2 using the structure of the table student and will copy all the records from table student to our new table student2. This became more useful when we add conditions to this by using SQL WHERE command.

How can you copy the structure of a table into another table without copying the data?

Question: How can I create a SQL table from another table without copying any values from the old table? Answer: To do this, the SQL CREATE TABLE syntax is: CREATE TABLE new_table AS (SELECT * FROM old_table WHERE 1=2);

How do I copy a table structure and data in SQL Server?

Right-click on the database name, then select "Tasks" > "Export data..." from the object explorer. The SQL Server Import/Export wizard opens; click on "Next". Provide authentication and select the source from which you want to copy the data; click "Next". Specify where to copy the data to; click on "Next".


For a simple schema copy use the like clause.

CREATE TABLE new_table_name (LIKE old_table_name INCLUDING ALL);

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.


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


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


How about

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

postgresql.org answer