I've been using the psql Postgres terminal to import CSV files into tables using the following
COPY tbname FROM
'/tmp/the_file.csv'
delimiter '|' csv;
which works fine except that I have to be logged into the psql terminal to run it.
I would like to know if anyone knows of a way to do a command similar to this from the Linux shell command line similar to how Postgres allows a shell command like bellow
/opt/postgresql/bin/pg_dump dbname > /tmp/dbname.sql
This allows the dumping of a database from the Linux shell without being logged into psql terminal.
To complete the previous answer, I would suggest:
As stated in The PostgreSQL Documentation (II. PostgreSQL Client Applications - psql) you can pass a command to
psql
with the switch-c
:The solution in the accepted answer will only work on the server and when the user executing the query will have permissions to read the file as explained in this SO answer.
Otherwise, a more flexible approach is to replace the SQL's
COPY
command with thepsql
's "meta-command" called\copy
which which takes all the same options as the "real" COPY, but is run inside the client (with no need for;
at the end):As per docs, the
\copy
command:In addition, if the
the_file.csv
contains the header in the first line, it can be recognized by addingheader
at the end of the above command:The most flexible way is to use a shell
HERE document
, which allows you to use shell variables inside your query, even inside (double or single) quotes: