Search code examples
sqlpostgresql-9.3pgadmin

How to export query results from Postgres to a CSV file


I am a beginner with Postgres and am trying to figure out how to export my data output (results) onto Excel or a CSV file. I was able to export my results onto a CSV file, but the results are not exactly what I received in my "Data Output" pane. Is there a way to have exactly what I am seeing in my Postgres Output Pane - Data Output in a CSV or Excel file?

Please help..


Solution

  • The copy command is the best way to do this:

    http://www.postgresql.org/docs/9.3/static/sql-copy.html

    COPY table_name [ ( column_name [, ...] ) ] FROM { 'filename' | PROGRAM 'command' | STDIN } [ [ WITH ] ( option [, ...] ) ]

    COPY { table_name [ ( column_name [, ...] ) ] | ( query ) } TO { 'filename' | PROGRAM 'command' | STDOUT } [ [ WITH ] ( option [, ...] ) ]

    where option can be one of:

    FORMAT format_name
    OIDS [ boolean ]
    FREEZE [ boolean ]
    DELIMITER 'delimiter_character'
    NULL 'null_string'
    HEADER [ boolean ]
    QUOTE 'quote_character'
    ESCAPE 'escape_character'
    FORCE_QUOTE { ( column_name [, ...] ) | * }
    FORCE_NOT_NULL ( column_name [, ...] )
    ENCODING 'encoding_name'