Start using PostgreSQL

Connect with psql

Open a PostgreSQL command-line session and identify the server, database, and role used by the connection.

psql is the standard PostgreSQL command-line client. You will use it through the whole course, so let’s make the first connection deliberate instead of lucky.

Start with the maintenance database that PostgreSQL creates:

psql postgres

That single argument is the database name. Everything else falls back to defaults: the local Unix socket as the host, port 5432, and your operating-system username as the role. On a fresh Homebrew install those defaults work, which is convenient and also why many people never learn what they connected to.

Know what you connected to

Inside psql, inspect the real connection:

\conninfo
SELECT version();
You are connected to database "postgres" as user "flavio"
via socket in "/tmp" at port "5432".

\conninfo answers three questions at once: which database, which role, which server. SELECT version(); tells you what the server is running. Make checking both a habit. Most “my table disappeared” panics are really “I am connected to the wrong database”.

A complete connection can specify each part explicitly:

psql -h localhost -p 5432 -U flavio -d postgres

-h forces a TCP connection instead of the socket, -U picks the role, -d picks the database. You will need these flags the first time you connect to a remote server, so it pays to try them locally first.

Type \q to leave the session.

The most common first-day error

Run psql with no arguments and you may see:

psql: error: connection to server on socket "/tmp/.s.PGSQL.5432" failed:
FATAL:  database "flavio" does not exist

Nothing is broken. Without a database name, psql tries a database named after your role, and nobody created one called flavio. Name the database and the error goes away: psql postgres.

One more distinction to keep sharp: the psql client is not the server. It is one program that talks to it. Closing psql does not stop PostgreSQL, and updating psql does not update the server.

Lesson completed

Take this course offline

Get every free book, course edition, and software download.

Get the download library →