green = shell command
blue = SQL / psql meta-command
| Tool / Query | Phase | Key commands | Use case |
|---|---|---|---|
| psql connection | psql |
psql -h localhost -U myuser -d mydb
psql "postgresql://myuser:pass@localhost:5432/mydb"
psql "postgresql://myuser@localhost/mydb?sslmode=require"
# avoid passwords in shell history. Use .pgpass:
# ~/.pgpass format: host:port:db:user:password
chmod 600 ~/.pgpass
# or use PGPASSFILE / PGPASSWORD env vars in scripts
|
Connection string URI is cleaner than individual flags in scripts. Never pass passwords via -W or shell history. Use ~/.pgpass with strict permissions or PGPASSWORD env var scoped to the command. sslmode=require for any non-localhost connection. |
| psql meta-commands | psql |
\l+
\c mydb
\dt+ schema.*
\d+ mytable
\di+ mytable
\df+ myfunction
\x auto
\timing on
\e
\copy mytable TO '/tmp/out.csv' CSV HEADER
|
\l+ includes sizes; \dt+ includes table sizes and descriptions; \d+ shows columns, constraints, indexes, and storage parameters. \x auto switches to expanded (vertical) output automatically for wide rows. \e opens the query buffer in $EDITOR. \copy runs client-side (no superuser needed); COPY is server-side. |
| psql scripting | psql |
psql -U myuser -d mydb -c "SELECT count(*) FROM events;"
psql -U myuser -d mydb -f migration.sql
psql -U myuser -d mydb -f migration.sql -v ON_ERROR_STOP=1
psql -U myuser -d mydb --csv -c "SELECT * FROM report;" > report.csv
psql -U myuser -d mydb -t -A -c "SELECT max(id) FROM events;"
# -t: tuples only, -A: unaligned; clean for shell variable capture
|
-v ON_ERROR_STOP=1 aborts the script on the first error: essential for migration scripts where partial execution leaves inconsistent state. -t -A strips headers and alignment for capturing single values into shell variables. --csv produces RFC 4180-compliant output. |
| pg_dump | backup |
pg_dump -U myuser -d mydb -Fc -f mydb.dump
pg_dump -U myuser -d mydb -Fd -j 4 -f mydb_dir/
pg_dump -U myuser -d mydb -t events --data-only -Fc -f events.dump
pg_dump -U myuser -d mydb --schema-only -f schema.sql
pg_dump -U myuser -d mydb -Fc | gzip > mydb_$(date +%Y%m%d).dump.gz
|
-Fc (custom format) is required for pg_restore selective restore and parallel jobs. -Fd -j 4 dumps in parallel: significantly faster on large databases. Never use plain SQL format for production backups; it can't be restored in parallel and has no TOC. Always verify with pg_restore --list before you need it. |
| pg_restore | backup |
pg_restore -U myuser -d mydb -Fc mydb.dump
pg_restore -U myuser -d mydb -Fc -j 4 mydb.dump
pg_restore --list mydb.dump | grep -i "TABLE DATA public events"
pg_restore --list mydb.dump > toc.txt
pg_restore -U myuser -d mydb -Fc -L toc.txt mydb.dump
pg_restore -U myuser -d mydb -Fc -t events mydb.dump
|
-j 4 restores in parallel: halves restore time on multi-core systems. Edit toc.txt to restore a subset (comment out lines with ;). -t events restores a single table. Run --list monthly on backup files to verify they're readable before an incident forces you to. |
| pg_basebackup | backup |
pg_basebackup -h localhost -U replicator -D /backup/base -Ft -z -P
pg_basebackup -h localhost -U replicator -D /backup/base -Xs -P --checkpoint=fast
pg_basebackup -h localhost -U replicator -D /replica/data -R -P
# -R writes standby.signal + postgresql.auto.conf for streaming replication
# verify backup integrity:
pg_verifybackup /backup/base
|
Physical base backup: faster to restore than pg_dump for large databases and required for PITR (point-in-time recovery). -R configures a new replica automatically. pg_verifybackup (PG13+) validates the backup manifest. Run it after every base backup, not just before a restore. |
EXPLAIN ANALYZE |
performance | EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT) SELECT ...;
EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) SELECT ... \gset
EXPLAIN (ANALYZE, BUFFERS, GENERIC_PLAN) SELECT $1 FROM t WHERE id = $1;
# wrap in a transaction and rollback to avoid side effects on writes:
BEGIN; EXPLAIN ANALYZE INSERT INTO ...; ROLLBACK;
# paste JSON output into: explain.dalibo.com or depesz.com
|
BUFFERS shows shared/local/temp buffer hits and reads: the difference between a plan hitting cache vs disk. GENERIC_PLAN (PG16+) shows the plan for a parameterised query before execution. Always wrap DML in a transaction and rollback when using ANALYZE to avoid committing test data. |
| pg_stat_statements | performance |
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
SELECT query, calls, mean_exec_time, total_exec_time, rows, shared_blks_hit, shared_blks_read
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 20;
SELECT query, calls, mean_exec_time
FROM pg_stat_statements
WHERE mean_exec_time > 100
ORDER BY mean_exec_time DESC;
SELECT pg_stat_statements_reset();
|
Workload-wide query profiling: identifies the highest-cumulative-time queries, not just the slowest individual calls. shared_blks_read high relative to shared_blks_hit signals missing indexes or undersized shared_buffers. Reset before a load test to get clean baselines. |
| slow query & lock analysis | performance |
SELECT pid, now() - query_start AS duration, state, wait_event_type, wait_event, query
FROM pg_stat_activity
WHERE state != 'idle'
AND query_start < now() - interval '5 seconds'
ORDER BY duration DESC;
SELECT blocked.pid, blocked.query, blocking.pid AS blocking_pid, blocking.query AS blocking_query
FROM pg_stat_activity blocked
JOIN pg_stat_activity blocking ON blocking.pid = ANY(pg_blocking_pids(blocked.pid))
WHERE cardinality(pg_blocking_pids(blocked.pid)) > 0;
SELECT pg_terminate_backend(<pid>);
|
First two queries are the incident response pair: find long-running queries, then find lock chains. pg_blocking_pids() (PG9.6+) recursively resolves the full blocking chain. pg_terminate_backend kills a connection; pg_cancel_backend cancels just the current query. Prefer cancel over terminate on production. |
| index analysis | performance |
SELECT schemaname, tablename, indexname, idx_scan, idx_tup_read, idx_tup_fetch,
pg_size_pretty(pg_relation_size(indexrelid)) AS index_size
FROM pg_stat_user_indexes
ORDER BY idx_scan ASC
LIMIT 20;
SELECT schemaname, tablename, attname, n_distinct, correlation
FROM pg_stats
WHERE tablename = 'events'
ORDER BY n_distinct;
SELECT pg_size_pretty(pg_relation_size('events')) AS table,
pg_size_pretty(pg_indexes_size('events')) AS indexes;
|
Unused indexes (idx_scan = 0) waste write performance and storage: drop them. correlation near ±1 means a B-tree index on that column will be highly effective; near 0 means a sequential scan may be cheaper than an index scan. Run after ANALYZE to get current statistics. |
| pgbench | performance |
pgbench -i -s 50 mydb
pgbench -c 10 -j 2 -T 60 mydb
pgbench -c 10 -j 2 -T 60 -P 5 mydb
pgbench -c 10 -j 2 -T 60 -f custom.sql mydb
pgbench -c 10 -j 2 -T 60 --latency-limit=50 mydb
# -s 50: scale factor 50 = 5M rows in pgbench_accounts
# -P 5: print progress every 5 seconds
|
Built-in TPC-B-like benchmarking. -s 50 generates a dataset large enough to not fit in cache: scale factor should exceed shared_buffers / 8MB for realistic results. -f custom.sql runs your own workload. --latency-limit counts transactions exceeding the threshold as failures. |
VACUUM & ANALYZE |
maintenance |
VACUUM ANALYZE mytable;
VACUUM VERBOSE ANALYZE mytable;
VACUUM FULL mytable;
SELECT schemaname, tablename, n_dead_tup, n_live_tup,
last_vacuum, last_autovacuum, last_analyze
FROM pg_stat_user_tables
WHERE n_dead_tup > 10000
ORDER BY n_dead_tup DESC;
SELECT relname, age(relfrozenxid) AS xid_age
FROM pg_class WHERE relkind = 'r'
ORDER BY xid_age DESC LIMIT 10;
|
VACUUM FULL reclaims disk space but takes an exclusive lock: only use in a maintenance window. Regular VACUUM is non-blocking. Transaction ID age above ~1.5B is an emergency (autovacuum_freeze_max_age default is 200M); above 2.1B, Postgres goes into read-only mode to prevent wraparound. Monitor xid_age in alerting. |
| bloat & table size | maintenance |
SELECT relname,
pg_size_pretty(pg_total_relation_size(relid)) AS total,
pg_size_pretty(pg_relation_size(relid)) AS table,
pg_size_pretty(pg_indexes_size(relid)) AS indexes,
pg_size_pretty(pg_total_relation_size(relid) - pg_relation_size(relid) - pg_indexes_size(relid)) AS toast
FROM pg_catalog.pg_statio_user_tables
ORDER BY pg_total_relation_size(relid) DESC
LIMIT 20;
SELECT pg_size_pretty(pg_database_size('mydb'));
vacuumdb -U postgres -d mydb --analyze-only -j 4
|
Surfaces TOAST overhead separately: large text/jsonb columns stored out-of-line are often the hidden driver of database size. vacuumdb -j 4 runs ANALYZE in parallel across tables. Run after a bulk load before query planning degrades. Use before adding indexes; stale stats make the planner choose wrong plans. |
| pg_activity | maintenance |
pip install pg_activity
pg_activity -U postgres -d mydb
pg_activity -U postgres --no-color --output=csv
# interactive keys: C (cancel query), K (terminate), F (filters)
# shows: active queries, wait events, locks, I/O, CPU per query
|
htop for PostgreSQL: real-time query activity, wait events, per-query CPU and I/O. Faster for incident triage than querying pg_stat_activity manually. --output=csv for scripted monitoring. No server-side component needed. |
| roles & privileges | security |
CREATE ROLE app_user LOGIN PASSWORD 'changeme';
GRANT CONNECT ON DATABASE mydb TO app_user;
GRANT USAGE ON SCHEMA public TO app_user;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO app_user;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO app_user;
REVOKE CREATE ON SCHEMA public FROM PUBLIC;
\du+
|
ALTER DEFAULT PRIVILEGES applies grants to future tables, without it, newly created tables are inaccessible to the app role. REVOKE CREATE ON SCHEMA public FROM PUBLIC closes a common privilege escalation vector present by default in PG14 and earlier. Always use least-privilege roles; never connect as postgres from applications. |
| pg_hba.conf & SSL | security |
# pg_hba.conf: minimal secure configuration:
# TYPE DATABASE USER ADDRESS METHOD
# local all postgres peer
# host mydb app_user 10.0.0.0/8 scram-sha-256
# hostssl mydb app_user 0.0.0.0/0 scram-sha-256
SHOW ssl;
SELECT name, setting FROM pg_settings WHERE name LIKE 'ssl%';
SELECT pg_reload_conf();
psql -U postgres -c "SELECT pg_reload_conf();"
|
Use scram-sha-256 everywhere: md5 is broken, trust is for local dev only. hostssl enforces TLS on the connection; host allows but doesn't require it. pg_reload_conf() applies pg_hba changes without a restart. Verify with SELECT ssl FROM pg_stat_ssl WHERE pid = pg_backend_pid();. |
| audit & connection audit | security |
SELECT client_addr, usename, application_name, state, count(*)
FROM pg_stat_activity
GROUP BY client_addr, usename, application_name, state
ORDER BY count DESC;
SELECT usename, ssl, client_addr, cipher
FROM pg_stat_ssl JOIN pg_stat_activity USING (pid)
WHERE ssl = false AND client_addr IS NOT NULL;
# enable query logging for audit (postgresql.conf):
# log_connections = on
# log_disconnections = on
# log_min_duration_statement = 1000 # log queries > 1s
|
First query shows connection pool saturation by client. Second surfaces non-SSL connections from remote hosts: any row returned is a finding. log_min_duration_statement is the lowest-overhead audit approach for slow query logging; pgaudit extension for full DDL/DML audit trails. |
| replication monitoring | replication |
SELECT client_addr, state, sent_lsn, write_lsn, flush_lsn, replay_lsn,
write_lag, flush_lag, replay_lag, sync_state
FROM pg_stat_replication;
SELECT now() - pg_last_xact_replay_timestamp() AS replication_lag
FROM pg_is_in_recovery();
SELECT pg_is_in_recovery();
SELECT pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn) AS lag_bytes
FROM pg_stat_replication;
|
Run the first query on the primary. replay_lag is wall-clock lag; pg_wal_lsn_diff gives lag in bytes: more actionable for alerting. Run the timestamp query on the replica. Alert on replay_lag > 30s or lag_bytes > 100MB depending on your RPO. sync_state = 'sync' confirms synchronous replication is active. |
| WAL & checkpoints | replication |
SELECT checkpoint_write_time, checkpoint_sync_time, buffers_checkpoint, buffers_clean,
buffers_backend, maxwritten_clean, buffers_alloc
FROM pg_stat_bgwriter;
SELECT pg_current_wal_lsn(), pg_walfile_name(pg_current_wal_lsn());
SELECT count(*) FROM pg_ls_waldir();
CHECKPOINT;
# postgresql.conf tuning signals:
# buffers_backend high → increase shared_buffers or checkpoint_completion_target
# maxwritten_clean high → increase bgwriter_lru_maxpages
|
buffers_backend high means the backend is writing dirty buffers itself because bgwriter can't keep up: a tuning signal, not an error. WAL file count growing unbounded indicates a replication slot holding WAL (check pg_replication_slots). CHECKPOINT forces a checkpoint before a planned maintenance operation. |
| replication slots | replication |
SELECT slot_name, slot_type, active, restart_lsn,
pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) AS retained_wal
FROM pg_replication_slots;
SELECT pg_drop_replication_slot('slot_name');
ALTER SYSTEM SET max_slot_wal_keep_size = '2GB';
SELECT pg_reload_conf();
|
Inactive replication slots retain WAL indefinitely. This is the most common cause of disk exhaustion in production Postgres. Alert on retained_wal > 5GB or when a slot has been inactive for > 1h. Set max_slot_wal_keep_size as a hard cap. Drop abandoned slots immediately; they are a disk-filling timebomb. |
No entries match this filter.