I am trying to:
psql -c "COPY ( SELECT * FROM "Users" LIMIT 10 ) TO STDOUT WITH CSV HEADER" > out.csv
However double quotes inside query ("Users"
) are removed and psql returns error that Relation users does not exist
. I tried to escape quotes like this \"Users\"
. but they are still removed. What can I do?
If you need to use the double quote inside the string, you can use the backslash character. Notice how the backslash in the second line is used to escape the double quote characters. And the single quote can be used without a backslash.
In PostgreSQL, double quotes (like "a red dog") are always used to denote delimited identifiers. In this context, an identifier is the name of an object within PostgreSQL, such as a table name or a column name. Delimited identifiers are identifiers that have a specifically marked beginning and end.
> Quotes and double quotes should be escaped using \.
Single quotes are used to indicate the beginning and end of a string in SQL. Double quotes generally aren't used in SQL, but that can vary from database to database. Stick to using single quotes. That's the primary use anyway.
And here is the right answer (it works for me):
echo 'COPY ( SELECT * FROM "Users" LIMIT 10 ) TO STDOUT WITH CSV HEADER' | psql > out.csv
And even better (it allows to use single and double quotes without any escaping):
psql > out.csv <<EOT
COPY
(SELECT id, email, "displayName", "firstName", "lastName", "displayName", 'some str' AS "someStr" FROM "Users" LIMIT 10)
TO STDOUT WITH CSV HEADER;
EOT
psql -c 'COPY ( SELECT * FROM "Users" LIMIT 10 ) TO STDOUT WITH CSV HEADER' > out.csv
In bash, you can use single quotes in strings provided you don't need to interpolate anything. Of course if your query contained single quotes, that wouldn't work but in your case you should be fine
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With