$ dbaguide.com / cheat-sheets / postgresql

psql CLI Quick Reference

Complete PostgreSQL Command Line Reference

v16 / v17 compatible
Updated: October 2026 · Production-grade
PG
01

Connection Commands

CommandDescription
psql -U postgres -d mydbConnect with specific user and database
psql -h 192.168.1.10 -p 5432 -U app_user -d prod_db
↳ Connect to remote server
psql "postgresql://user:pass@host:5432/dbname"
↳ Connection string (URI) format
psql -U postgres -d mydb -c "SELECT version();"
↳ Run single command and exit
psql -U postgres -f /path/to/script.sql
↳ Execute SQL file
PGPASSWORD=secret psql -U user -d dbPass password via environment variable
psql -U postgres -d mydb -qQuiet mode (suppress messages)
.pgpass file format: hostname:port:database:username:password — chmod 600 required.
05

Variables & Settings

CommandDescription
\set VAR valueDefine a variable
\unset VARDelete a variable
\setList all variables
SELECT :'VAR';Use variable in query
\echo :VARPrint variable value
\setenv PGTZ 'UTC'Set environment variable
Example Usage
\set schema public SELECT * FROM :'schema'.users LIMIT 10;
+

Help & Useful Commands

\?List all meta commands
\h SELECTSQL command syntax help
\gxExecute last query in expanded mode
\watch 5Repeat last query every 5 seconds
\errverboseShow last error in full detail
02

Meta Commands (Backslash Commands)

Database & Connection
\l or \listList all databases
\c mydbSwitch database
\conninfoShow active connection info
\qQuit psql
Tables & Schemas
\dtList tables in current schema
\dt public.*All tables in public schema
\d tablenameShow table structure
\d+ tablenameDetailed table info (including size)
\dnList schemas
\dn+Schemas + permissions
\dvList views
\dmList materialized views
\diList indexes
\dfList functions
\dsList sequences
Users & Privileges
\duList roles and users
\dp tablenameShow table privileges
\z tablename\dp Same as \dp
Appending + to any meta command (e.g. \dt+, \df+) displays size, description, and owner details. \? lists all meta commands.
08

.psqlrc Sample Configuration

-- ~/.psqlrc (auto-loaded on every psql session) \set QUIET 1 \timing on \x auto \set PROMPT1 '%[%033[1;32m%]%n@%/%[%033[0m%]# ' \set HISTSIZE 10000 \set COMP_KEYWORD_CASE upper \unset QUIET
03

Output & Format Settings

CommandDescription
\xToggle expanded (vertical) mode
\x autoAutomatic expanded mode
\aToggle aligned / unaligned mode
\tShow rows only (tuple only mode)
\timingMeasure and display query duration
\pset border 2Set border thickness
\pset format csvCSV format output
\o /tmp/output.txtRedirect output to file
\oStop redirecting to file
\HToggle HTML output mode
04

Query & Script Management

CommandDescription
\eEdit query in external editor ($EDITOR)
\ef function_nameEdit function definition in editor
\ev view_nameEdit view definition in editor
\gRe-execute last query
\g /tmp/result.csvSave last query result to file
\i /path/to/file.sqlExecute SQL file
\ir relative/path.sqlExecute SQL file at relative path
\sShow command history
\s /tmp/history.sqlSave history to file
06

COPY & Data Import/Export

CommandDescription
\copy table TO '/tmp/out.csv' CSV HEADER
↳ Export table to CSV (client-side)
\copy table FROM '/tmp/in.csv' CSV HEADER
↳ Import CSV into table
\copy (SELECT ...) TO '/tmp/q.csv' CSV HEADER
↳ Export query result to CSV
\copy table TO STDOUTExport to standard output
\copy is client-side; COPY is server-side. File permissions differ.
07

Debugging & Diagnostic Queries

pg_stat_activity · pg_stat_user_tables · pg_locks
Active Connections
-- Active connections SELECT pid, usename, application_name, state, query FROM pg_stat_activity WHERE state != 'idle';
Table Sizes
-- Table sizes SELECT relname, pg_size_pretty( pg_total_relation_size(relid)) FROM pg_stat_user_tables ORDER BY pg_total_relation_size(relid) DESC;
Long-Running Queries
-- Long-running queries SELECT pid, now() - query_start AS duration, query FROM pg_stat_activity WHERE state = 'active' AND now() - query_start > interval '5 min';
Lock Waiters
-- Lock waiters SELECT pid, relation::regclass, mode, granted FROM pg_locks WHERE NOT granted;