This article is half-done without your Comment! *** Please share your thoughts via Comment ***
In this post, I am sharing a demonstration on how to export or import CSV data using the PostgreSQL COPY command.
The CSV files are most famous for the necessary data migration activities. Database developer does not need to write or create any particular database link between two servers.
They can easily import data in CSV and export that CSV into another server and also CSV file does not have any data length limitation like any other XLS file.
User can store millions of records into CSV file.
This technique is preferred only for temporary purposes, and if it continues the process, the user has to write some automated process like database server replication.
PostgreSQL provides the COPY command to import or export CSV data into the PostgreSQL table.
Let me demonstrate this:
First, I create one table and import data from CSV file. I have already created a CSV file with sample data. Make sure that, your table column and CSV column would be same.
You can create this CSV file using a comma delimited save as option of Microsoft excel.
1 2 3 4 5 |
CREATE TABLE tbl_testcsv ( rno integer, name character varying ); |
Now COPY the data from CSV file into the table:
1 2 3 |
COPY tbl_testcsv FROM 'E:\dbrnd.com\Postwork\testcsv.csv' WITH DELIMITER ',' CSV HEADER; |
After executing of COPY command, you can check the result:
1 |
SELECT *FROM tbl_testcsv; |
Add some more records in Table and then we export the data into CSV file:
1 2 3 4 |
INSERT INTO tbl_testcsv VALUES (9,'YRQ'),(10,'QWE') ,(11,'MNB'),(12,'FGH'); |
Now, export this data using the COPY command:
1 2 3 4 |
COPY tbl_testcsv TO 'E:\dbrnd.com\Postwork\testcsv.csv' WITH DELIMITER ',' CSV HEADER; --Query returned successfully: 12 rows affected, |
Now, check your CSV file. You can find newly inserted data:
You can also define a particular column or write a full select statement in the COPY command:
Below is a sample script.
1 2 3 4 |
COPY tbl_testcsv(rno) TO 'E:\dbrnd.com\Postwork\testcsv.csv' WITH DELIMITER ',' CSV HEADER; |
1 2 3 4 |
COPY (SELECT rno,name FROM tbl_testcsv WHERE rno=8) TO 'E:\dbrnd.com\Postwork\testcsv.csv' WITH DELIMITER ',' CSV HEADER; |
This is a full detailed example of Postgres COPY command, please test this sample and let me know for further assistance.