PostgreSQL Copy Table: A Step-by-Step Guide with Practical Examples
Summary: in this tutorial, we will show you step by step how to copy an existing table including table structure and data by using the various forms of PostgreSQL copy table statement.
Introduction to PostgreSQL copy table statement
To copy a table completely, including both table structure and data, you use the following statement:
To copy a table structure without data, you add the WITH NO DATA
clause to the CREATE TABLE
statement as follows:
To copy a table with partial data from an existing table, you use the following statement:
The condition of the WHERE
clause of the query defines which rows of the existing table that you want to copy to the new table.
Note that all the statements above copy table structure and data but do not copy indexes and constraints of the existing table.
PostgreSQL copy table example
First, create a new table named contacts
for the demonstration:
In this table, we have two indexes: one index for the primary key and another for the UNIQUE
constraint.
Second, insert some rows into the contacts
table:
Output:
Third, create a copy the contacts
to a new table such as contacts_backup
table using the following statement:
This statement creates a new table called contact_backup
whose structure is the same as the contacts
table. Additionally, it copies data from the contacts
table to the contact_backup
table.
Fourth, verify the data of the contact_backup
table by using the following SELECT
statement:
Output:
It returns two rows as expected.
Fifth, examine the structure of the contact_backup
table:
Output:
The output indicates that the structure of the contact_backup
table is the same as the contacts
table except for the indexes.
Sixth, add the primary key and UNIQUE
constraints to the contact_backup
table using the following ALTER TABLE
statements:
Finally, view the structure of the contact_backup
table:
Output:
Summary
- Use the
CREATE TABLE table_name AS TABLE table_copy
statement to make a copy of a table to a new one.