In this PostgreSQL tutorial, we will learn How to Connect Databases in Linux, if you’re using Linux as an operating system and have PostgreSQL installed, this step-by-step tutorial will take you through the process of connecting to a PostgreSQL.
- Step 1: Start PostgreSQL Service
- Step 2: Switch to PostgreSQL User
- Step 3: Get access to the PostgreSQL Shell (psql)
- Step 4: List Databases
- Step 5: Connect to a Database
- Step 6: Verify the Connection
Step 1: Start PostgreSQL Service
To begin, if you have already installed PostgreSQL, start the PostgreSQL service by executing the following command in the Linux terminal.
sudo service postgresql start

Step 2: Switch to PostgreSQL User
Switch to the PostgreSQL user account in order to connect to the database by executing the following command.
sudo -i -u postgres

Step 3: Get access to the PostgreSQL Shell (psql)
After switching to the PostgreSQL user, access the PostgreSQL shell using the following command.
psql

Step 4: List Databases
Once you’re in the PostgreSQL shell, get the list of the available databases by executing the below command.
\l

Step 5: Connect to a Database
Use the following command syntax to connect to your database.
\c <databasename>
Replace <databasename> with the name of the database you want to connect to. For example, from the list of available databases, connect to the “postgres” database using the below command.
\c postgres
You’ll need to enter your username and password if the database you’re connected to needs authentication. To create the connection, provide the needed credentials.
After executing the above command, you see the message on the terminal “You are now connected to database ‘postgres’ as user ‘postgres’ “. as shown in the below picture.

Step 6: Verify the Connection
You can run SQL queries and interact with the database after successfully connecting to the PostgreSQL database. To check the connection, run the below query.
SELECT version();

The above query displays the version of PostgreSQL you’re connected to.
Conclusion
In this PostgreSQL tutorial, we have learned how to connect to the PostgreSQL database on the Linux system. By following the step-by-step tutorial, you should be able to connect to a PostgreSQL database, perform SQL queries, and interact with the database using the PostgreSQL shell (psql).
You may like to read:
- How to use PostgreSQL To_Number
- How to Download and Install PostgreSQL on Windows
- PostgreSQL Update Limit
I am Bijay having more than 15 years of experience in the Software Industry. During this time, I have worked on MariaDB and used it in a lot of projects. Most of our readers are from the United States, Canada, United Kingdom, Australia, New Zealand, etc.
Want to learn MariaDB? Check out all the articles and tutorials that I wrote on MariaDB. Also, I am a Microsoft MVP.