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

Viewed 31325

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?

3 Answers

Please try this format as I got the output from the same:

psql -h $host -p $port -q -U $user -d $Dbname -c "SELECT \"Employee-id\",\"Employee-name\" FROM Employee_table" >> Employee_Date.csv

I need the output in a CSV file.

Related