Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run PostgreSQL queries from the command line

I inserted a data into a table....I wanna see now whole table with rows and columns and data. How I can display it through command?

like image 294
Manu Lakaster Avatar asked Oct 30 '13 05:10

Manu Lakaster


People also ask

How do I run a query in PostgreSQL?

To do this in PL/pgSQL, use the PERFORM statement: PERFORM query ; This executes query and discards the result. Write the query the same way you would write an SQL SELECT command, but replace the initial keyword SELECT with PERFORM .

What is psql command line tool?

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.

How do I connect to postgres from terminal?

Username [postgres]: On a Mac or Windows, you are able to connect to the default instance by simply hitting enter at the shell or command prompt when trying to run psql and keying in the password.


1 Answers

psql -U username -d mydatabase -c 'SELECT * FROM mytable'

If you're new to postgresql and unfamiliar with using the command line tool psql then there is some confusing behaviour you should be aware of when you've entered an interactive session.

For example, initiate an interactive session:

psql -U username mydatabase  mydatabase=# 

At this point you can enter a query directly but you must remember to terminate the query with a semicolon ;

For example:

mydatabase=# SELECT * FROM mytable; 

If you forget the semicolon then when you hit enter you will get nothing on your return line because psql will be assuming that you have not finished entering your query. This can lead to all kinds of confusion. For example, if you re-enter the same query you will have most likely create a syntax error.

As an experiment, try typing any garble you want at the psql prompt then hit enter. psql will silently provide you with a new line. If you enter a semicolon on that new line and then hit enter, then you will receive the ERROR:

mydatabase=# asdfs  mydatabase=# ;   ERROR:  syntax error at or near "asdfs" LINE 1: asdfs     ^ 

The rule of thumb is: If you received no response from psql but you were expecting at least SOMETHING, then you forgot the semicolon ;

like image 196
Grant Avatar answered Oct 29 '22 07:10

Grant