Forrest logo
back to the psql tool

postgresql:export:csv

Store result of a PostgreSQL query as a CSV file
$ psql -d dbname -t -A -F"," -c "${query}" > ${file_name}
try on your machine

This command is written for the psql command-line tool, which is used to interact with PostgreSQL databases. The command supports several options to execute queries and redirect the output to a file.

Here is the breakdown of each component:

  • psql: The command itself, used to invoke the psql tool.

  • -d dbname: Specifies the name of the database (dbname) to connect to.

  • -t: This option stands for "tuples only" and is used to produce output in a table-like format. With this option, column names and footers are omitted.

  • -A: This option stands for "unaligned" and is used to produce output in an unaligned format, separating each field with the delimiter specified by the -F option (in this case, a comma). This is useful when you want to process the output programmatically.

  • -F",": Specifies the field delimiter to be a comma (,). This delimiter is used when outputting the query results in unaligned mode.

  • -c "${query}": Executes the query specified by the ${query} variable. The curly braces $() are used for command substitution, allowing the value of the query variable to be included in the command.

  • > ${file_name}: Redirects the output of the psql command to the file specified by the ${file_name} variable. The > operator is used for output redirection.

Overall, this command connects to a PostgreSQL database, executes a specified query, formats the output as unaligned with comma delimiters, and saves the result in a file.

This explanation was created by an AI. In most cases those are correct. But please always be careful and never run a command you are not sure if it is safe.
back to the psql tool