10

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?

2
  • Another good reason to avoid identifiers that need quoting...
    – user330315
    Sep 27, 2014 at 22:27
  • So you say that all table names and column names should be lowercased?
    – user606521
    Sep 27, 2014 at 23:14

2 Answers 2

12

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
6
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

2
  • And what I can do in case when I have to use both double and single quotes in my SQL query?
    – user606521
    Sep 27, 2014 at 20:18
  • I tried what you wrote but it still removes double quotes from query - maybe this is done by psql for some reason?
    – user606521
    Sep 27, 2014 at 20:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.