PostgreSQL | Database | Connect to a Specified Database

This page explains how to connect to a database when connecting to PostgreSQL, and how to switch from the currently connected database to another database in psql.

Specify the Database to Connect to with psql Options

When connecting to PostgreSQL with psql, if you do not specify the database to connect to, psql connects to a database with the same name as the role being used.

For example, when connecting as the postgres role as shown below, psql connects to the postgres database, which has the same name as the role.

C:\Users\kimkc>psql -U postgres
postgres 사용자의 암호:
psql (12.2)
도움말을 보려면 "help"를 입력하십시오.

postgres=#   >>>>>>>>>>>>> the prompt displays the name of the currently connected database.

The name of the currently connected database is shown in the prompt.

Connect to a Database with the \c Command

After connecting to PostgreSQL with psql, use \c, one of psql’s meta-commands, to connect to a database other than the currently connected database.

Now try connecting to the devkuma database. Run the following.

C:\Users\kimkc>psql -U postgres
postgres 사용자의 암호:
psql (12.2)
도움말을 보려면 "help"를 입력하십시오.

postgres=# \c devkuma
접속정보: 데이터베이스="devkuma", 사용자="postgres".
devkuma=#

You are now connected to the devkuma database. The database name shown in the prompt has also changed to devkuma. You can also use \connect instead of \c.

Check the Name of the Currently Connected Database

You can use PostgreSQL’s current_database function to check the name of the currently connected database.

Run the following.

devkuma=# select current_database();
 current_database
------------------
 devkuma
(1개 행)


devkuma=#

The currently connected database, devkuma, has been retrieved.

This page explained how to connect to a specified database.