Connecting to PostgreSQL

1. Connecting with psql Client

psql -h localhost -p 5432 -U alice -d shop
psql -W                       # force password prompt
psql "postgresql://alice:s3cret@db.example.com:5432/shop?sslmode=require"
FlagPurpose
-hHost
-pPort
-UUsername
-dDatabase
-c "SQL"Run single command
-f file.sqlExecute script
-XSkip ~/.psqlrc

2. Using Connection Strings

FormExample
URIpostgresql://user:pwd@host:5432/db?sslmode=require
Keyword/valuehost=db user=alice dbname=shop sslmode=require
Multi-hostpostgresql://host1,host2/db?target_session_attrs=read-write
UNIX socketpostgresql:///shop?host=/var/run/postgresql

3. Setting Connection Parameters

ParameterEffect
connect_timeoutSeconds before giving up
application_nameVisible in pg_stat_activity
optionsPer-connection GUCs, e.g. -c statement_timeout=5000
target_session_attrsany, read-write, read-only, primary, standby, prefer-standby
channel_bindingprefer / require / disable

4. Using Password File

# ~/.pgpass  (chmod 600)
# hostname:port:database:username:password
db.example.com:5432:shop:alice:S3cret!
*:*:*:postgres:adminpwd
Note: Must be 0600 permissions or PostgreSQL ignores it.

5. Setting psql Environment Variables

VariablePurpose
PSQL_HISTORYHistory file path
PSQLRCOverride ~/.psqlrc
PSQL_EDITOREditor for \e
PSQL_PAGERPager command
PAGERFallback pager

6. Connecting to Remote Server

psql -h db.prod.internal -p 5432 -U app -d orders \
     "sslmode=verify-full sslrootcert=~/certs/ca.pem"
PrereqSetting
Serverlisten_addresses='*' + firewall rule on 5432
pg_hba.confhost or hostssl rule for client CIDR
Authscram-sha-256 or cert

7. Using SSL Connections

sslmodeBehavior
disableNo SSL
allowTry non-SSL, fall back to SSL
preferTry SSL first (default)
requireSSL mandatory, no cert verify
verify-caSSL + CA verified
verify-fullSSL + CA + hostname match (recommended)

8. Checking Connection Status

\conninfo                              -- psql meta-command
SELECT current_user, current_database(),
       inet_server_addr(), inet_server_port(),
       version();
SELECT pid, usename, application_name, client_addr, state, query
  FROM pg_stat_activity WHERE pid = pg_backend_pid();

9. Switching Databases

CommandEffect
\c dbnameReconnect to same host as same user
\c dbname userSwitch user too
\c dbname user host portFull reconnect

10. Disconnecting from Server

MethodCommand
psql exit\q or Ctrl-D
Server-side terminateSELECT pg_terminate_backend(pid);
Cancel query onlySELECT pg_cancel_backend(pid);