How to Connect to PostgreSQL Database Clusters with psql

To connect to PostgreSQL database clusters from the command line, you need two things:

  • A PostgreSQL client on your local computer. We recommend psql, the PostgreSQL interactive terminal, which you can get by installing PostgreSQL.

  • The database cluster’s connection details, which tells your client how to connect to the cluster.

PostgreSQL Cluster Connection Details

You can find a database cluster’s connection details in the control panel. From the Databases page, click the name of the cluster to go to its Overview page.

Databases Overview screen showing connection string

In the Connection Details section, the drop-down menu has three options:

  • Connection parameters, which is meant for application configuration and is incompatible with clients like psql.

  • Connection string, which is a condensed string that you can pass to a client on the command line. PostgreSQL’s connection string documentation goes into detail on the structure, but the general format is postgresql://username:password@hostname:port/database.

  • Flags, which is a complete psql command that supplies the connection variables as individual flags.

We recommend the flags format because the readability can help if you want to customize the way you connect. The only required parameter is sslmode, but PostgreSQL supports a lot of options for customizing connections.

By default, the control panel doesn’t reveal the cluster’s password for security reasons. Click Copy to copy connection details with the password, or click show-password to reveal the password.

Connecting with psql

To connect using the flags format, paste the entire command from the control panel in your terminal:

PGPASSWORD=password psql -U doadmin -h psql-do-user-example-0.db.ondigitalocean.com -p 25060 -d defaultdb --set=sslmode=require

To connect using the connection string, pass the string from the control panel in quotes to psql in your terminal:

psql "postgresql://doadmin:password@psql-do-user-example-0.db.ondigitalocean.com:25060/defaultdb?sslmode=require"

When you connect successfully, your terminal changes to the psql prompt, which displays the name of the database you’re connected to:

defaultdb=>

From here, you can change databases or users, execute SQL queries, and perform other database administration tasks. Learn more about psql in our SQL cheat sheet and the official psql documentation.