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

6May/0813

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 (13) 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?

  6. try creating a view and using it instead of the query. hope this helps.

  7. Your post was useful

    Could you tell me how I can include the data in double quotes ?

    \o /tmp/moocow.csv
    SELECT foo,bar FROM whatever;
    \o

    and the output like

    “foo”,”bar”
    “fdata”,”bdata”
    “fdata1″,”bdata2″

    Appreciate your help !

  8. This works
    psql dbname -F , –no-align -c “SELECT * FROM table”

  9. I have to export several queries from different tables but the COPY command always overwrites the file.
    Is there any solution for this ?

  10. thanks! Could you tell me how to replace ‘,’ by ‘.’ in the file CSV

    please

    • @sonia,

      You can do like this,
      COPY (SELECT foo,bar FROM whatever) TO ‘/tmp/dump.csv’
      delimiters ‘.’ WITH CSV HEADER

      Bala


Leave a comment

(required)

No trackbacks yet.