I need to create a Linux shell script to run a PostgreSQL SQL query and export the results in CSV Format. By doing some research I came to know there are two ways I can do it such as below:
using an SQL query
COPY table_name TO ‘file_name.csv' DELIMITER ',' CSV HEADER;using
psql\copy table_name to 'filename.csv’ csv header
I have tried both from SQL server out of which I found the first method needs administrative permission, which I don't want.
I have tried the second method and am able to write the PostgreSQL query output to a CSV file as well, but now I need to do that from a shell script, where I am facing the below issue. I am writing inside the script as follows:
psql -U username -d database -c $'
\copy(WITH var(collectionMonth) as (values(\'$collectionMonth\'))
SELECT CONCAT(var.collectionMonth, LPAD(mfv2.integer_value::text,2,\'0\')) as "collection_date" FROM var,
meta_field_value mfv2 WHERE mfv2.meta_field_name_id=8 TO \'/home/my.csv\' csv HEADER;'
It shows “syntax error near \copy”. How to fix this? I know the error is because of the \ in front of the copy command.