https://www.postgresql.org/docs/13/app-psql.html
\timing on
\pset footer on
-- change field separator if query may contain commas
-- \f '|'
-- \f ',' -- default
\timing
\a
\! pwd
\o filename.csv
select * from ....
\f ',' -- reset
\a
with comments
\timing on -- how long each query takes (usually only relevant to optimization of long queries)
\pset footer on -- displays the 'n rows' count after a query
\f ',' -- set the field separator for unaligned query output, deault is | (same as \pset fieldsep '')
\a -- if current output format is unliagned then toggle it to aligned (in this case to unaligned, for csv output)
\! pwd -- \! escapes to a subshell, in this run 'pwd'
\o filename.csv -- output future query results (excl error messages) to filename in cwd
select * from .... -- the query
\f '|' -- sets the field sep back to default |
\a -- toggle alignment, back to aligned in this case
\o -- resets future query results to stdout
Other \pset options
csv_fieldsep
fieldsep
footer
format (aligned, csv, unaligned)
pager - pipe output to specific program
recordsep
tuplesonly
other commands
\cd directory_name
\o or \out filename or can pipe to command