PostgreSQL COPY command - how to write a query in several lines

I am using a database PostgreSql. I want to select some data from a database and copy it to a csv file . And it works:

\COPY (SELECT * from table) TO '/csv_dir/csv_file.csv';

My problem is that it only works if the whole command is on only one line. How to write a COPY command in multiple lines? This sql is what I want to add to more rows.

+4
source share
1 answer

As an internal command psql, and like other commands starting with a backslash, it \copyshould fit on one line.

, - .

COPY \copy, STDOUT stdout . :

$ psql -At -d test <<EOQ >outfile
COPY
 (select 1,2
  union
  select 3,4)
TO STDOUT;
EOQ

:

$ cat outfile
1   2
3   4

psql, COPY , :

test=> \t
Showing only tuples.
test=> \o outfile
test=> copy
test->  (select 1,2
test(> union
test(> select 3,4)
test-> to stdout;
test=> \o
test=> \t
Tuples only is off.

\o outfile , \o .

+2

Source: https://habr.com/ru/post/1535935/


All Articles