How do I copy data from one table to another in postgres using copy command
To efficiently transfer data from one table to another in PostgreSQL, use the \COPY
meta-command:
- Export source table data as a CSV file:
- Import the CSV file into the destination table:
This seamlessly preserves the CSV format and headers. Moreover, \COPY
can be executed from client interfaces, such as psql, without requiring server file access permissions.
Comprehensive Data Copy Guide
There's no one-size-fits-all solution when it comes to data transfer between tables. You might need different commands for unique scenarios. Let's examine some common requirements:
Cloning a table (structure + data)
The statement above creates new_table
, duplicating all data and structure from existing_table
.
Copying specific columns
In this case, you're selecting specific columns (col1, col2
) from existing_table
and inserting them into new_table
(colA, colB
). Make sure your columns align!
Structure first, data next
new_table
is first created with the structure of existing_table
, and then data is inserted from existing_table
into new_table
.
Copy only some data (filtered)
This command will copy only the rows that meet the filter condition from existing_table
to new_table
.
Remove duplicates during copy
Distinct values only, based on unique_column
, from existing_table
will be copied to the new_table
.
Transaction safety net
Every operation is wrapped in a transaction for peace of mind. Either all the operations are successful, or none are—just like committing a crime, except legal.
Backup table before shenanigans
Backup the table specifically before performing any risky operations, because sometimes prevention is better than cure.
Advanced Data Copy Methods
The \COPY
command serves well for file-based data transport. Yet, PostgreSQL has more techniques for fine-grained control.
Data copy with conditional filters
Copy complex datasets
Visualization
Visualize the data transfer from one table to another in PostgreSQL as a well-organized transfer of goods:
Akin to moving cargo, the COPY command shuttles the valuable data from one stop to the next with efficiency.
Safeguard and Optimize your Data Transfer
Pre-import assessment
Before importing the data, consider if the destination table:
- Has indexes that require pausing.
- Contains triggers that need disabling.
- Needs any extra constraints.
Post-import verification
After successfully importing the data:
- Verify the data quality and counts.
- If indexing was paused, rebuild it.
- Enable the previously disabled triggers.
Was this article helpful?