psql - save results of command to a file

后端 未结 10 1179
日久生厌
日久生厌 2020-12-12 09:10

I\'m using psql\'s \\dt to list all tables in a database and I need to save the results.

What is the syntax to export the results of a psql command to a

相关标签:
10条回答
  • 2020-12-12 09:53

    From psql's help (\?):

    \o [FILE] send all query results to file or |pipe

    The sequence of commands will look like this:

    [wist@scifres ~]$ psql db
    Welcome to psql 8.3.6, the PostgreSQL interactive terminal
    
    db=>\o out.txt
    db=>\dt
    db=>\q
    
    0 讨论(0)
  • 2020-12-12 09:53

    If you got the following error

    ufgtoolspg=> COPY (SELECT foo, bar FROM baz) TO '/tmp/query.csv' (format csv, delimiter ';');
    ERROR:  must be superuser to COPY to or from a file
    HINT:  Anyone can COPY to stdout or from stdin. psql's \copy command also works for anyone.
    

    you can run it in this way:

    psql somepsqllink_or_credentials -c "COPY (SELECT foo, bar FROM baz) TO STDOUT (format csv, delimiter ';')"  > baz.csv
    
    0 讨论(0)
  • 2020-12-12 09:57

    Use o parameter of pgsql command.

    -o, --output=FILENAME send query results to file (or |pipe)

    psql -d DatabaseName -U UserName -c "SELECT * FROM TABLE" -o /root/Desktop/file.txt
    
    0 讨论(0)
  • 2020-12-12 10:00

    \copy which is a postgres command can work for any user. Don't know if it works for \dt or not, but general syntax is reproduced from the following link Postgres SQL copy syntax

    \copy (select * from tempTable limit 100) to 'filenameinquotes' with header delimiter as ','
    

    The above will save the output of the select query in the filename provided as a csv file

    EDIT:

    For my psql server the following command works this is an older version v8.5

    copy (select * from table1) to 'full_path_filename' csv header;
    
    0 讨论(0)
提交回复
热议问题