Connecting & Database Objects
Connecting with psql#
Connect using flags, a connection URI, or standard libpq environment variables (PGHOST, PGPORT, PGUSER, PGDATABASE):
# Flags
psql -h db.example.com -p 5432 -U app_user -d mydb
# Connection URI
psql "postgresql://[email protected]:5432/mydb?sslmode=require"
For non-interactive scripts, store credentials in ~/.pgpass (chmod 600 ~/.pgpass) instead of passing passwords on the command line:
# hostname:port:database:username:password
db.example.com:5432:mydb:app_user:secret_passwordEssential psql meta-commands#
| Command | Description |
|---|---|
\l+ | List databases with sizes and tablespaces |
\c mydb | Switch connection to mydb |
\dn+ | List schemas and permissions |
\dt+ | List tables with sizes in current search_path |
\d+ my_table | Describe columns, indexes, constraints, and triggers |
\du+ | List roles and memberships |
\x auto | Toggle expanded display automatically for wide rows |
\timing on | Show execution time for every query |
Databases, schemas, and search_path#
PostgreSQL organizes objects in a strict hierarchy: Cluster -> Database -> Schema -> Table / Index / View / Function.
- Databases are completely isolated (you cannot join tables across databases without
postgres_fdwordblink). - Schemas are namespaces inside a database (
publicis created by default).
Check and configure search_path (which schemas are searched for unqualified table names):
SHOW search_path;
CREATE SCHEMA app;
ALTER ROLE app_user SET search_path = app, public;Tablespaces#
Tablespaces map a logical name to a separate OS directory (for example, placing archive tables or temporary files on a different disk):
CREATE TABLESPACE fast_ssd LOCATION '/mnt/nvme/pg_tbs';
CREATE TABLE events (...) TABLESPACE fast_ssd;
-- List tablespaces
\db+