patternsqlMajor
Export remote Postgres table to CSV file on local machine
Viewed 0 times
localfilepostgrescsvexportmachineremotetable
Problem
I have read-only access to a database on a remote server. So, I can execute:
But on that server I don't have permissions to create/save a file, so I need to do this on my local machine.
When I connect to the remote database, how can I execute a command to save the file on my local machine instead of the remote server?
Or, how can I execute a Linux command to connect to the remote database, execute a query, and save the output as a file to my local machine?
COPY products TO '/tmp/products.csv' DELIMITER ',';But on that server I don't have permissions to create/save a file, so I need to do this on my local machine.
When I connect to the remote database, how can I execute a command to save the file on my local machine instead of the remote server?
Or, how can I execute a Linux command to connect to the remote database, execute a query, and save the output as a file to my local machine?
Solution
Both the approaches already suggested appear to be unnecessarily complicated.
Just use
Because it's a
See the
Just like
A generally inferior alternative that can be useful in a few limited situations is to use:
and use the
Just use
psql's built-in \copy command, which works just like server-side COPY but does a copy over the wire protocol to the client and uses client paths.Because it's a
psql backslash command you omit the trailing semicolon, eg:\copy products TO '/tmp/products.csv' CSV DELIMITER ','See the
\copy entry in the manual for the psql command and the COPY command documenation for more detail.Just like
COPY you can use \copy with a (SELECT ...) query instead of a table name when copying data out (but not in).A generally inferior alternative that can be useful in a few limited situations is to use:
psql -t -P format=unaligned -P fieldsep_zero=on -c 'SELECT * FROM tablename'and use the
-o flag or shell output redirection to write the output to a file. You should almost always use \copy in preference to this.Code Snippets
\copy products TO '/tmp/products.csv' CSV DELIMITER ','psql -t -P format=unaligned -P fieldsep_zero=on -c 'SELECT * FROM tablename'Context
StackExchange Database Administrators Q#36235, answer score: 37
Revisions (0)
No revisions yet.