PostgreSQL Shell Commands

In this tutorial, we will learn to use some of the psql commands to do PostgreSQL operations in the psql shell.

Once we start the psql shell, we will be asked to provide details like server, database, port, username and password. You may choose to go with the defaults (password is mandatory though).

PostgreSQL psql shell

psql Comands

Connect to Database

</>
Copy
 \c databasename

This psql command is used to connect to a specific database. You have to provide the database name after \c. This is like use command in sql shells. Once connected, we can run SQL queries on the database.

In the following example, we connected to a database named mydb.

psql command - connect to database

Describe Available Relations

</>
Copy
 \d

This psql command is used to describe available relations in the database. Tables are an example for relations.

In the following example, we have run \d command on mydb database. It listed all the available relations. For each relation, we get four properties: Schema in which the relation is, Name of the relation, Type of relation, and the Owner for that relation.

psql command - describe available relations

Describe Relation

</>
Copy
 \d relationname

While \d command described the list of all available relations in a database, this psql command describes about a specific relation. We have to provide the relation name after \d.

In the following example, we have run this psql command on a table.

psql command - describe relation

List of Console Commands and Options

</>
Copy
 \?

This psql command is quite useful. You do not need to remember the whole list of commands.

psql command \? - list of commands

The list is big. At the end of the command prompt, you will get -- More --. Click enter to get the next commands in the list.

List of Available SQL syntax Help Topics

</>
Copy
 \h

This psql command list all avilable SQL syntax.

psql commands - sql syntax help
psql commands - sql syntax help

Quit psql shell

</>
Copy
 \q

This psql command helps to quit out of the PostgreSQL shell.

psql command - quit

Press any key, and you are out of psql shell.

Conclusion

In this PostgreSQL Tutorial, we learned about some of the useful psql commands with examples.