0
0
PostgresqlHow-ToBeginner · 3 min read

How to Connect to PostgreSQL: Simple Steps and Examples

To connect to PostgreSQL, use the psql command-line tool or a connection string with parameters like host, port, user, password, and dbname. For example, run psql -h localhost -U username -d dbname to start a connection.
📐

Syntax

The basic syntax to connect to PostgreSQL using the psql command-line tool is:

  • psql -h <host> -p <port> -U <user> -d <dbname>
  • host: The server address (e.g., localhost)
  • port: The port number PostgreSQL listens on (default is 5432)
  • user: Your PostgreSQL username
  • dbname: The database name you want to connect to

You can also use a connection string format: postgresql://user:password@host:port/dbname.

bash
psql -h localhost -p 5432 -U myuser -d mydatabase
💻

Example

This example shows how to connect to a PostgreSQL database named testdb on your local machine using the user testuser. You will be prompted for the password.

bash
psql -h localhost -U testuser -d testdb
Output
psql (14.5) Type "help" for help. testdb=>
⚠️

Common Pitfalls

Common mistakes when connecting to PostgreSQL include:

  • Using the wrong port number (default is 5432)
  • Forgetting to specify the database name
  • Incorrect username or password
  • Not having PostgreSQL server running or accessible
  • Missing required client tools like psql

Always check your connection parameters and ensure the server is running.

bash
Wrong: psql -h localhost -U wronguser -d mydb
Right: psql -h localhost -U correctuser -d mydb
📊

Quick Reference

ParameterDescriptionDefault
-hHost address of the PostgreSQL serverlocalhost
-pPort number PostgreSQL listens on5432
-UUsername to connect ascurrent system user
-dDatabase name to connect tosame as username if omitted
Connection StringFull URI format for connectionN/A

Key Takeaways

Use the psql command with -h, -p, -U, and -d options to connect to PostgreSQL.
The default port for PostgreSQL is 5432 unless configured otherwise.
Ensure the PostgreSQL server is running and accessible before connecting.
Use correct username and database names to avoid connection errors.
You can also connect using a full connection string URI format.