How to Connect to PostgreSQL Databases with psql

You can access DigitalOcean PostgreSQL Databases from the command line using psql, the PostgreSQL interactive terminal. To do this, you’ll need two things:

  • PostgreSQL installed on your local machine, which lets you use the psql command in a terminal.

  • The connection string for the database you want to connect to.

You can find a database’s connection string in the control panel. From the Databases page, click the name of the cluster you want to connect to, which will bring you to its Overview page. In the Connection Details section, open the drop-down menu and select Connection string.

Databases Overview screen showing connection string

You can also use the Flags format with the psql command, which supplies the variables as individual flags that are easier to read and customize. The default format, Connection parameters, is meant for application configuration and is incompatible with psql.

Whichever version you choose, your control panel doesn’t show the password for security reasons. Click Copy to copy the connection string with the password. If you want to highlight and copy the text from the screen directly, first click show-password in the connection string to reveal the password.

In your terminal, pass the connection string in quotes to psql to connect. This connection string will connect you to the automatically-created database, defaultdb, as the admin user, doadmin.

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

When you connect successfully, you’ll arrive at 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. You can learn more about psql in our SQL cheat sheet and the official psql documentation.