63

I would like to export a single Postgres table's data into a .csv file. Can anyone give me an example of how to do that?

bryanbraun
  • 3,025
  • 2
  • 26
  • 38
kallem
  • 741
  • 2
  • 8
  • 13
  • 1
    Possible duplicate http://stackoverflow.com/questions/1120109/export-postgres-table-to-csv-file-with-headings – o3o May 23 '12 at 09:52
  • Possible duplicate of [Export Postgres table to CSV file with headings](http://stackoverflow.com/questions/1120109/export-postgres-table-to-csv-file-with-headings) – Ethan Furman Jan 19 '17 at 20:52

3 Answers3

85

In psql:

\copy tablename to 'filename' csv;
Peter Eisentraut
  • 35,221
  • 12
  • 85
  • 90
63

First, log into the PostgreSQL console via the command line with the psql command.

To export:

\connect database_name;
\copy my_table TO 'my_table.csv' CSV;
\q

To import:

\connect database_name;
\copy my_table FROM 'my_table.csv' DELIMITER ',' CSV;
\q

Done!


Or, from a shell script!

export PGPASSWORD=dbpass
psql --dbname=mydb --username=dbuser --host=127.0.0.1 -c "COPY (SELECT * FROM widget) TO stdout DELIMITER ',' CSV HEADER" > export.csv

Bonus Advice Use pgcli, it's way better than psql

Nick Woodhams
  • 11,977
  • 10
  • 50
  • 52
12

When logged into psql:

COPY tablename TO 'filename';

For more details, see this: http://www.postgresql.org/docs/current/static/sql-copy.html

crmpicco
  • 16,605
  • 26
  • 134
  • 210
Joel Rein
  • 3,608
  • 1
  • 26
  • 32
  • 3
    And that will copy the data to a server-accessible file. Which may or may not be the goal. For a client-side copy (inside `psql`) use `\copy`. – Milen A. Radev Jan 25 '11 at 09:15
  • 6
    also you have to be a superuser to use `COPY`, but not to use `\copy` – redbmk Mar 20 '13 at 20:59