Skip to content

Instantly share code, notes, and snippets.

@jimathyp
Last active November 3, 2022 19:33
Show Gist options
  • Select an option

  • Save jimathyp/17cf82f6073f9135757392c527a2c8f6 to your computer and use it in GitHub Desktop.

Select an option

Save jimathyp/17cf82f6073f9135757392c527a2c8f6 to your computer and use it in GitHub Desktop.

Output postgres query to CSV

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment