PostgreSQL | Connecting to PostgreSQL with psql | Connecting and Disconnecting from PostgreSQL

This page explains how to connect to PostgreSQL with psql and how to disconnect from PostgreSQL.

Connecting to PostgreSQL

psql is a command-line tool that lets you connect to databases created in PostgreSQL and retrieve data from tables. In Windows, use psql from Command Prompt.

First, start Command Prompt.

To connect to PostgreSQL with psql, run the following command. In practice, this connects to the specified database created in PostgreSQL.

psql -h {host name} -p {port number} -U {user name} -d {database name}

The host name is the host name or IP address where PostgreSQL is running. The default is localhost, so you can omit it when connecting to PostgreSQL running on the local host.

The port number is the port used by PostgreSQL. The default is 5432, which is set during PostgreSQL installation, so you can omit it unless you use a different port.

Immediately after installing PostgreSQL, only the postgres role is created as a superuser, so specify -U postgres. If you omit the user name, the operating system user name is used.

Note: In PostgreSQL, users and groups are generally managed together as roles.

For the database name, specify the database to connect to. If you omit it, psql connects to a database with the same name as the user. The postgres database is created automatically, and when you connect as the postgres role, you connect to the postgres database.

When specifying all connection options, the command looks like this:

psql -h localhost -p 5432 -U postgres -d postgres

If the host is localhost, you can omit the host name, and you can also omit the port number. If you connect to a database with the same name as the user, you can omit the database name as well, so the following command is equivalent to the one above.

psql -U postgres

Now run it.

C:\>psql -U postgres
Password for user postgres:

psql waits for the login password of the user you are connecting as. The password for postgres is the one specified when PostgreSQL was installed. Enter it and press the Enter key. If it is entered correctly, the following screen appears.

C:\>psql -U postgres
Password for user postgres:
psql (12.2)
Type "help" for help.

postgres=#

While connected, the prompt is displayed as database_name=#. Here, because the connection is to the postgres database, it is displayed as postgres=#.

Exit psql and Disconnect from PostgreSQL

To exit psql and disconnect from PostgreSQL, run the following command.

\q
C:\>psql -U postgres
Password for user postgres:
psql (12.2)
Type "help" for help.

postgres=# \q

C:\>

psql exits and the connection to PostgreSQL is closed.

This page explained how to connect to PostgreSQL with psql and how to disconnect.