55

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
  • 2,775
  • 1
  • 24
  • 36
kallem
  • 661
  • 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

81

In psql:

\copy tablename to 'filename' csv;
Peter Eisentraut
  • 33,335
  • 12
  • 80
  • 87
48

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,259
  • 10
  • 49
  • 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
  • 15,553
  • 24
  • 124
  • 206
Joel Rein
  • 3,485
  • 1
  • 25
  • 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