Published on

Using psql to export Postgres tables to CSV

Authors

From time to time you need to export the data in a table to a text file for analysis. If you are using Postgres then the excellent psql command line tool has you covered. To export a table:

  1. Login to the DB you need: psql -U dbUsername -d dbName -h hostname -W
  2. The W option will prompt you for a password
  3. You can leave out the -h hostname if you are on the host running the DB
  4. Then to create the csv from the table you want run: \copy yourTableName to 'yourfileName' csv;
  5. Then to quit: \q

The copy command has a bunch more configurations which you can read about here.