Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

psql - write a query and the query's output to a file

In postgresql 9.3.1, when interactively developing a query using the psql command, the end result is sometimes to write the query results to a file:

boron.production=> \o /tmp/output
boron.production=> select 1;
boron.production=> \o
boron.production=> \q
$ cat /tmp/output
?column? 
----------
        1
(1 row)

This works fine. But how can I get the query itself to be written to the file along with the query results?

I've tried giving psql the --echo-queries switch:

   -e, --echo-queries
       Copy all SQL commands sent to the server to standard output as well.
       This is equivalent to setting the variable ECHO to queries.

But this always echoes to stdout, not to the file I gave with the \o command.

I've tried the --echo-all switch as well, but it does not appear to echo interactive input.

Using command editing, I can repeat the query with \qecho in front of it. That works, but is tedious.

Is there any way to direct an interactive psql session to write both the query and the query output to a file?

like image 378
Wayne Conrad Avatar asked Dec 06 '13 20:12

Wayne Conrad


People also ask

How do I export a PostgreSQL query to a CSV file?

The easiest but the most efficient way to export data from a Postgres table to a CSV file is by using the COPY command. COPY command generates a CSV file on the Database Server. You can export the entire table or the results of a query to a CSV file with the COPY TO command.

What is :: In psql?

The type 'string' syntax is a generalization of the standard: SQL specifies this syntax only for a few data types, but PostgreSQL allows it for all types. The syntax with :: is historical PostgreSQL usage, as is the function-call syntax.


2 Answers

You can try redirecting the stdout to a file directly from your shell (Win or Linux should work)

psql -U postgres -c "select 1 as result" -e nomedb >> hello.txt

This has the drawback of not letting you see the output interactively. If that's a problem, you can either tail the output file in a separate terminal, or, if in *nix, use the tee utility:

psql -U postgres -c "select 1 as result" -e nomedb | tee hello.txt

Hope this helps!

Luca

like image 155
Luca Abbati Avatar answered Sep 18 '22 14:09

Luca Abbati


I know this is an old question, but at least in 9.3 and current versions this is possible using Query Buffer meta-commands shown in the documentation or \? from the psql console: https://www.postgresql.org/docs/9.3/static/app-psql.html

\w or \write filename
\w or \write |command

Outputs the current query buffer to the file filename or pipes it to the shell command command.
like image 36
Blockhead Avatar answered Sep 17 '22 14:09

Blockhead