Search code examples
postgresqlpsql

How to save psql output to a file?


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

What is the command to export the results of a psql command to a file?


Solution

  • 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
    

    Then any db operation output will be written to out.txt. Enter '\o' to revert the output back to console.

    db=>\o