Postgresql export to CSV

A common database task is a custom report from the console. This usually invovles a CSV file since it’s human readable and imports into Microsoft Excel. It’s very easy to do this in PostgreSql 8. Just use the copy directive like this:

COPY (select * from table_name) 
TO '/tmp/table_name.csv' WITH CSV HEADER;

For example, if I want to dump select * from yoda where state='jedi' to CSV, my SQL may look something like this:

COPY (select * from yoda where state='jedi') 
TO '/tmp/jedi.csv' WITH CSV HEADER;