How To Export Table/QueryResult To CSV File On PostgreSQL

 

PostgreSQL supports the CSV file format as a native. You can import data from a CSV file and add it to a table, or you can save the result of any query as a CSV file.

You can also redirect the output to stdout and zip it before the file is written to the disk.

We do all this with the COPY command. Let’s create a test table, insert data into it, and then export from this table to a file with CSV extension.

 

Create a Table and Insert Data Into It:

 

For CSV output; You must specify a file path after the TO.

 

Our file is ready; We can see the contents with the bash command “Cat”.

 

We can change the shape of our output by giving different parameters. Below, I’m adding a new record first. I then create the file using the COPY command. Lastly, I’m leaving psql to view the contents of the file.

 

The details of the query I shared above can be seen below;

Şahap Aşçı
Author: Şahap Aşçı

Leave a Reply

Your email address will not be published. Required fields are marked *