psql Quick Reference
The PostgreSQL CLI’s backslash meta-commands — inspect schemas, time queries, and stay productive without a GUI.
Connect
- Connect
psql -h host -U user -d dbname- URL
psql postgres://user:pass@host:5432/db- Switch database
\c otherdb- Run a file
psql -d db -f script.sql· inside:\i script.sql- Quit
\q
Inspect (meta-commands)
- List databases
\l- List tables
\dt· all relations:\d- Describe a table
\d tablename— columns, types, indexes- List indexes / views
\di·\dv- List schemas / roles
\dn·\du- List functions
\df- Search objects
\dt *user*— pattern match
Work faster
- Expanded rows
\x— vertical output for wide tables (toggle)- Time every query
\timing- Output to file
\o out.txt— then queries write there;\oto stop- Edit query in $EDITOR
\e- Re-run last query
\g- Save/use a snippet
\set q 'select 1'then:q
Diagnose
- Query plan
EXPLAIN ANALYZE SELECT …;— estimated vs actual rows- Active queries
SELECT * FROM pg_stat_activity;- Table / db size
SELECT pg_size_pretty(pg_total_relation_size('t'));- Kill a query
SELECT pg_cancel_backend(pid);(orpg_terminate_backend)