68

I need to execute postgresql queries from command line using psql -c command. For every psql command, it opens a new tcp connection to connect to the database server and execute query which is a overhead for large number of queries.

Currently I can execute single query like this:

psql -U postgres -h <ip_addr> -c "SELECT * FROM xyz_table;"

When I tried to execute multiple queries as below, but only the last query got executed.

psql -U postgres -h <ip_addr> -c "SELECT * FROM xyz_table; SELECT * FROM abc_table;"

Can anyone help me and tell me the proper way to do it?

Pankaj Goyal
  • 1,448
  • 3
  • 15
  • 25
  • 11
    Both statements are executed but only the last one returns as a result set. Check the manual: http://www.postgresql.org/docs/current/interactive/app-psql.html – Frank Heikens Mar 02 '15 at 07:38
  • 1
    Thanks, @FrankHeikens! I think you should also add that as an answer (or propose an edit to the accepted answer). The top answer promotes the misinformation that only one command gets processed. – Wildcard Oct 15 '16 at 00:41

5 Answers5

96

-c processes only one command. Without it however psql expects commands to be passed into standard input, e.g.:

psql -U postgres -h <ip_addr> <database_name> << EOF
SELECT * FROM xyz_table;
SELECT * FROM abc_table;
EOF

Or by using echo and pipes.

keltar
  • 17,711
  • 2
  • 37
  • 42
25

Specify each command with consecutive -c flags:

psql -c "select now()" -c "select version()" -U postgres -h 127.0.0.1

The output of the above command:

              now              
-------------------------------
 2017-12-26 20:25:45.874935+01
(1 row)

                                                 version                                                  
----------------------------------------------------------------------------------------------------------
 PostgreSQL 9.6.2 on x86_64-pc-linux-gnu, compiled by gcc (Ubuntu 5.3.1-14ubuntu2) 5.3.1 20160413, 64-bit
(1 row)
toraritte
  • 6,300
  • 3
  • 46
  • 67
Cyril Damm
  • 283
  • 5
  • 7
23

Using echo and a pipe to fit it on a single line:

echo 'SELECT * FROM xyz_table; \n SELECT * FROM abc_table' | psql -U postgres 
Salami
  • 2,849
  • 4
  • 24
  • 33
17

The --file parameter executes a file's content

psql -U postgres -h <ip_addr> -f "my_file.psql"

All the output will be sent to standard output

http://www.postgresql.org/docs/current/static/app-psql.html

Clodoaldo Neto
  • 118,695
  • 26
  • 233
  • 260
0

The "clean" solution is to pass multiple -c options:

$ psql ... -c 'select 1 as a' -c "select 'foo' as b"
 a
---
 1
(1 row)

  b
-----
 foo
(1 row)

Notable benefit: you can use backslash commands this way, e.g. \x.

(@leo-y points this out in a comment)

hraban
  • 1,819
  • 1
  • 17
  • 27