Ian P. Christian's Personal Blog Random witterings from pookey

6May/085

Outputting from Postgres to CSV

I can never remember how to output to a CSV file from postgres, and end up having to google it time and time again - so I'm making a note of it here mostly for my own use :)

\f ','
\a
\t
\o /tmp/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;
Comments (5) Trackbacks (0)
  1. After much pain with line endings:

    COPY (SELECT foo,bar FROM whatever) TO ‘/tmp/dump.csv’ WITH CSV HEADER

  2. I also can never remember how to do this, and I always google it, and end up here. So, thank you for keeping this handy!!!

  3. Saves so much effort looking for a simple example!

  4. I run a lot of queries from the bash command line or from scripts, so here’s a tip:

    If you run into this error: “ERROR: must be superuser to COPY to or from a file,” try this:

    echo “COPY (SELECT foo from BAR) TO STDOUT with CSV HEADER” | psql -o filename.csv database_name

  5. @Ben,

    Your solution works well in version 8.4.2 and it shows a syntax error in version 8.1

    copy to file command in postgresql 8.1 does not accept a query . it can copy whole table but not a query

    do u have any solution for 8.1?


Leave a comment


No trackbacks yet.