11

I googled a lot but..

How do I escape single quote in command line query of psql ?

psql -t -A -F $'\t' postgresql://zzzz:5432/casedb -U qqqq -c 'select id,ext_ids ->> 'qwe' as qwe from data ORDER BY qwe' > /jdata/qwe.tab

Results in error

ERROR:  column "qwe" does not exist
LINE 1: select id,ext_ids ->> qwe as qwe from data...
Mureinik
  • 297,002
  • 52
  • 306
  • 350
expert
  • 29,290
  • 30
  • 110
  • 214

2 Answers2

12

In Postgres you can use dollar-quoted strings:

select id,ext_ids ->> $$qwe$$ as qwe from data ORDER BY qwe;
-- or
select id,ext_ids ->> $anything$qwe$anything$ as qwe from data ORDER BY qwe;
klin
  • 112,967
  • 15
  • 204
  • 232
4

You could just use double quotes (") for the shell quoting and single quotes (') for the SQL quoting:

psql -t -A -F $'\t' postgresql://zzzz:5432/casedb -U qqqq -c "select id,ext_ids ->> 'qwe' as qwe from data ORDER BY qwe" > /jdata/qwe.tab
# Here ------------------------------------------------------^---------------------------------------------------------^
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • 2
    You have to be wary of using double quotes on the shell command line since any special characters like '$', '*', and '?' inside of them will be evaluated. – Robert Casey Oct 03 '18 at 18:22