Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass SQL query to psql as a argument containing double quotes

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?

like image 507
user606521 Avatar asked Sep 27 '14 19:09

user606521


People also ask

How do you handle double quotes in SQL query?

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.

Can you use double quotes in PostgreSQL?

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.

How do I escape double quotes in PostgreSQL?

> Quotes and double quotes should be escaped using \.

Can you use double quotation marks in SQL?

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.


2 Answers

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
like image 191
user606521 Avatar answered Sep 19 '22 00:09

user606521


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

like image 39
triggerNZ Avatar answered Sep 21 '22 00:09

triggerNZ