Sub topic 2
Connecting to a Database with psql
This chapter covers how psql finds and reaches a PostgreSQL server, how to verify the connection, and how to diagnose the errors you will meet most often. It assumes you can use a terminal, know basic SQL, and have PostgreSQL installed locally or have access to a server. It builds on the idea that one server holds many databases. A connection always attaches to exactly one of them.
What a connection is
psql is the command-line client that ships with PostgreSQL. Each time you start it, psql opens one session to one database on one server. To open a session, it needs four things:
- A host (the machine running the server, or a Unix socket directory).
- A port (5432 by default).
- A role (the user name).
- A database name.
Anything you leave out is filled in from defaults, so you can often type just psql. The defaults are a common source of surprise, so this chapter spells them out.
The explicit form
The clearest way to connect is to name every part:
psql -h localhost -p 5432 -U postgres -d mydb| Flag | Long form | Meaning |
|---|---|---|
| `-h` | `--host` | Server host name, IP address, or socket directory |
| `-p` | `--port` | TCP port of the server |
| `-U` | `--username` | Role to connect as |
| `-d` | `--dbname` | Database to connect to |
If the server requires a password, psql prompts for it. The prompt does not echo what you type. To skip the prompt in scripts, use a password file or the PGPASSWORD variable, both described below.
Where defaults come from
When you omit a flag, psql looks for a value in this order:
- The command-line flag.
- An environment variable such as
PGHOST,PGPORT,PGUSER, orPGDATABASE. - A built-in default.
The built-in defaults are:
- Host: the local Unix-domain socket, not
localhost. The two can behave differently, as explained under authentication. - Port: 5432.
- User: your operating system user name.
- Database: the same name as the role you connect as.
That last default explains a classic error. If your OS user is alice and no database named alice exists, running psql fails with database "alice" does not exist. The fix is to name a database that does exist, for example psql -d postgres.
Connection strings
Instead of separate flags, you can pass one connection string. psql accepts two syntaxes:
psql "postgresql://postgres@localhost:5432/mydb"
psql "host=localhost port=5432 user=postgres dbname=mydb"The URI form is convenient for copying from application configuration. Put quotes around it, because characters such as & and ? mean something to your shell. A URI can also carry options after a ?, such as ?sslmode=require.
> Avoid putting the password in a URI. It ends up in your shell history and in the process list, where other users on the machine can see it.
Safer ways to supply a password:
~/.pgpass: a file with lines in the formhost:port:database:user:password. On Unix, psql ignores it unless its permissions are0600. Runchmod 600 ~/.pgpass.PGPASSWORD: an environment variable. It is simple, but the PostgreSQL documentation discourages it because environment variables can be visible to other processes on some systems.-W: forces a password prompt.-wdoes the opposite and never prompts, which is useful in automation because the command fails instead of hanging.
Verifying where you are
After connecting, confirm the session is what you intended. The \conninfo meta-command prints the database, role, and how psql reached the server:
\conninfoTypical output looks like this:
You are connected to database "mydb" as user "postgres" on host "localhost" (address "::1") at port "5432".If you connected over a Unix socket, the output says so and names the socket directory instead of a host address. Newer versions of psql also report SSL details when a connection is encrypted.
The prompt gives a second clue. By default it looks like mydb=#. The part before = is the current database. The character after it shows your privilege level: # means you are a superuser, and > means you are not. A prompt ending in - instead of = means psql is waiting for the rest of an unfinished statement, usually because of a missing semicolon.
You can also ask the server directly with SQL:
SELECT current_database(), current_user, inet_server_addr(), inet_server_port();inet_server_addr() returns NULL over a Unix socket, which is a handy way to tell the two apart.
Switching databases inside a session
You do not need to quit psql to look at another database. The \c meta-command closes the current connection and opens a new one:
\c otherdb
\c otherdb aliceThe second form also changes the role. PostgreSQL cannot run a query across two databases in one session. Switching with \c is the normal way to move between them, and it resets session state such as temporary tables and SET values.
Authentication: why localhost and the socket differ
The server decides whether to accept you using rules in a file named pg_hba.conf. Each rule matches a connection type (local socket or TCP), a database, a role, and an address, then names an authentication method. Common methods are:
peer: for socket connections, accepts you if your OS user name matches the role.scram-sha-256(and the oldermd5): requires a password.trust: accepts anyone, which is only appropriate on isolated development machines.
This is why psql -U postgres can fail with Peer authentication failed for user "postgres" while psql -h localhost -U postgres asks for a password and succeeds. The first uses the socket and the peer rule. The second uses TCP and a password rule. When a connection is rejected, the error message names the rule type that matched, which tells you where to look.
Common errors
| Message | Likely cause | What to try |
|---|---|---|
| `connection refused` on port 5432 | Server not running, wrong port, or not listening on that address | Check the service status and `-p`; check `listen_addresses` on the server |
| `No such file or directory` for a socket | Wrong socket directory, or server stopped | Use `-h localhost`, or pass the socket directory to `-h` |
| `password authentication failed` | Wrong password or wrong role | Re-check `-U`; reset the role's password if you are an administrator |
| `no pg_hba.conf entry for host ...` | No rule allows this address, role, or database, or SSL is required | Ask the administrator to add a rule, or try `sslmode=require` |
| `database "x" does not exist` | The default database name does not exist | Add `-d postgres` or the correct name |
| `FATAL: role "x" does not exist` | Default OS user name is not a PostgreSQL role | Add `-U` with an existing role |
psql includes a companion command that tests reachability without logging in:
pg_isready -h localhost -p 5432It reports whether the server is accepting connections and sets its exit status accordingly, so it works in health checks.
A connection checklist
The following sequence works well when you meet a new server:
- Run
pg_isreadyagainst the host and port to rule out network or server problems. - Connect to the
postgresmaintenance database with an explicit-U. - Run
\conninfoand confirm host, port, role, and database. - Check whether the prompt ends in
#or>to know your privilege level. - Use
\cto move to the database you actually want to explore.
Exercise
You run psql as the OS user dana and get FATAL: database "dana" does not exist. Which default caused this, and give two ways to fix it.
Show answer
When no database is named, psql uses the connecting role's name, which defaults to the OS user name, so it looked for a database called dana. Fix it by naming a real database, for example psql -d postgres, or by setting PGDATABASE=postgres in the environment.
Exercise
psql -U postgres fails with Peer authentication failed, but psql -h localhost -U postgres prompts for a password. Why do the two commands differ?
Show answer
Without -h, psql connects over the local Unix socket, where pg_hba.conf matches a peer rule that requires the OS user name to equal the role. With -h localhost, psql connects over TCP, which matches a different rule that uses password authentication.
Exercise
After connecting, how can you tell from the prompt alone whether you are a superuser, and what does a prompt ending in - mean?
Show answer
A prompt such as mydb=# means superuser, and mydb=> means a regular role. A prompt ending in -, such as mydb-#, means psql is waiting for the rest of an unfinished SQL statement, usually because the terminating semicolon is missing.