Export data to CSV in PostgreSQL

PostgreSQL provides an easy way to export our query result into a CSV file, let’s see how we can do this.

1. Let’s connect to PostgreSQL with psql command:

user@host:~$ psql -p 5433 -U dba dbname

2) Type \o /home/user/data.csv, it will export the query result to /home/user/data.csv file.

dbname=> \o /home/user/data.csv

3) Type query that you want to export

dbname=> select * from table;

Now we should have our data.cvs file with all the query result.

4. Quit the psql command.

dbname=> \q

I hope this works for you.