6
votes

Quick question (I hope!): if I use \i to feed an input file into psql, can I get the output from the queries to be saved into a file? If so, how? Thanks!!

3

3 Answers

7
votes

Based on the documentation, the \o is for directing output to a file.

7
votes

Using \o, as recommended by others, is a good solution. Just for fun, though, another way to do this would be to pipe the input file to psql from the command line, rather than using the \i command. Then you could re-direct the output to another file. For example:

psql < input.sql > output.txt

This has some interesting side effects. For example, if you have timing turned on (\timing on), then using \o would not cause the timing results to be piped to the output file, but re-direction would. Same thing with \echo statements.

6
votes

Sure can:

dbname=> \o /home/outputfile.csv
dbname=> select * from table;
dbname=> \q

Output will be streamed to the file. Or

dbname=> \o

To stop streaming to file.