Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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...
like image 280
expert Avatar asked Jul 29 '16 11:07

expert


People also ask

How do I escape a single quote in PostgreSQL?

PostgreSQL also accepts “escape” string constants, which are an extension to the SQL standard. An escape string constant is specified by writing the letter E (upper or lower case) just before the opening single quote, e.g., E'foo' .

How do you escape a single quote in SQL?

The simplest method to escape single quotes in SQL is to use two single quotes. For example, if you wanted to show the value O'Reilly, you would use two quotes in the middle instead of one. The single quote is the escape character in Oracle, SQL Server, MySQL, and PostgreSQL.

How do you exit a query in PostgreSQL?

The meta-command for exiting psql is \q .

How do you escape a double quote in Postgres?

> Quotes and double quotes should be escaped using \.


2 Answers

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;
like image 183
klin Avatar answered Oct 25 '22 16:10

klin


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 ------------------------------------------------------^---------------------------------------------------------^
like image 40
Mureinik Avatar answered Oct 25 '22 16:10

Mureinik