Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 924
Pankaj Goyal Avatar asked Mar 02 '15 06:03

Pankaj Goyal


People also ask

How do I run multiple queries in PostgreSQL?

Batch mode You can write multiple psql commands and SQL statements in one text file (say, named statements. sql ), and then use the command psql congress -af statements. sql to execute them all. Use “ ; ” to signal the end of each SQL statement in the file.

How do I run multiple SQL queries at once?

To run a query with multiple statements, ensure that each statement is separated by a semicolon; then set the DSQEC_RUN_MQ global variable to 1 and run the query. When the variable is set to zero, all statements after the first semicolon are ignored.

What is psql shell?

Description. psql is a terminal-based front-end to PostgreSQL. It enables you to type in queries interactively, issue them to PostgreSQL, and see the query results. Alternatively, input can be from a file or from command line arguments.


1 Answers

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

like image 126
keltar Avatar answered Sep 22 '22 20:09

keltar