Connecting with psql
It is 2 a.m., the app is down, and the only tool on the server is a terminal. psql, PostgreSQL's command-line client, is always there. A DBA who is fluent in it can connect, look around and fix things in seconds.
The rule
Host, port, user, database — then backslash commands to look around.
Every connection needs four facts. psql takes them as flags, as a URI, or from environment variables:
psql -h db1.pedal.internal -p 5432 -U pedal_admin -d pedal
psql "postgresql://pedal_admin@db1.pedal.internal:5432/pedal"
export PGHOST=db1.pedal.internal PGUSER=pedal_admin PGDATABASE=pedal
psqlAnything you leave out has a default: the host is the local Unix socket, the port is 5432, and both the user and the database default to your operating-system user name. That is why sudo -u postgres psql works on a fresh server: you become the postgres OS user, psql connects as role postgres to database postgres over the local socket.
To avoid typing passwords, put them in ~/.pgpass (host:port:database:user:password, one per line) and make it private with chmod 600, or psql will ignore it.
Inside psql, lines starting with a backslash are meta-commands handled by psql itself, not SQL:
| Command | Shows |
|---|---|
\conninfo |
who and where you are connected |
\l |
databases |
\c reports |
switch to another database |
\dn |
schemas |
\dt |
tables in the search path |
\d rentals |
columns, indexes and constraints of a table |
\du |
roles |
\x |
toggle expanded (vertical) output |
\timing |
show how long each query takes |
\? / \h ALTER TABLE |
help for meta-commands / for SQL |
\q |
quit |
SQL statements run only when psql sees a semicolon. The prompt changes from pedal=> to pedal-> while a statement is unfinished, and a # instead of > means you are a superuser.