Thomas' Tech Tips

Redirect output of SQL query to a file from inside psql

26 April 2023 - Thomas Damgaard

It is sometimes handy save the output of an SQL query to a file.

In PostgreSQL command-line client psql, the \o option can be used to redirect the output of an SQL query to a file.

How to use \o:

\o results.txt

This will cause the output of subsequent SQL queries to be redirected to the file results.txt.

The output of any query run after this command will be redirected to results.txt until \o is used again to set a different file, or until the redirection is turned off by running \o without specifying any filename.

This is useful when you want to save the results of a query for later analysis or to share with others. Or if you need to work with datasets that are too big to be shown on the terminal.

Filed under: howto, postgresql, psql, sql, tips

Back to article list