Outputting from Postgres to CSV


f ','
a
t
o /home/john/moocow.csv
SELECT foo,bar FROM whatever;
o
q
 
If a field has newlines, this will break. You can do something like  this instead….. 
 
SELECT foo, bar, '"' || REPLACE(REPLACE(field_with_newilne, 'n', '\n'), '"', '""') || '"'
FROM whatever;
 
Then you can import the data into another database if needed:
copy whatever(foo,bar) FROM
'/home/john/moocow.csv' DELIMITER ','
CSV HEADER;