How to execute multiple queries using psql command from bash shell?

DatabasePostgresqlShell

Database Problem Overview


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?

Database Solutions


Solution 1 - Database

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

Solution 2 - Database

at least from 9.6.2 this approach works as well:

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

          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)

Solution 3 - Database

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 

Solution 4 - Database

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPankaj GoyalView Question on Stackoverflow
Solution 1 - DatabasekeltarView Answer on Stackoverflow
Solution 2 - DatabaseCyril DammView Answer on Stackoverflow
Solution 3 - DatabaseSalamiView Answer on Stackoverflow
Solution 4 - DatabaseClodoaldo NetoView Answer on Stackoverflow