Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

psql - save results of command 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 syntax to export the results of a psql command to a file?

like image 395
pstanton Avatar asked Mar 16 '11 20:03

pstanton


People also ask

How do I save SQL query output to a file?

Click Query, and then click Results to File. Enter and then execute the SQL statement. In the Save Results dialog box, specify the following settings: Save In: Select a directory in which to save the file.

Which command is used to save SQL command output to file?

Using the o command to Export Output to Files.


2 Answers

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 
like image 113
jhwist Avatar answered Sep 17 '22 13:09

jhwist


The psql \o command was already described by jhwist.

An alternative approach is using the COPY TO command to write directly to a file on the server. This has the advantage that it's dumped in an easy-to-parse format of your choice -- rather than psql's tabulated format. It's also very easy to import to another table/database using COPY FROM.

NB! This requires superuser privileges and will write to a file on the server.

Example: COPY (SELECT foo, bar FROM baz) TO '/tmp/query.csv' (format csv, delimiter ';')

Creates a CSV file with ';' as the field separator.

As always, see the documentation for details

like image 22
intgr Avatar answered Sep 17 '22 13:09

intgr