PostgreSQL command line cheatsheet
Magic words:
psql -U postgres
If run with -E flag, it will describe the underlaying queries of the \ commands (cool for learning!).
Most \d commands support additional param of __schema__.name__ and accept wildcards like *.*
\q: Quit/Exit\c __database__: Connect to a database\d __table__: Show table definition including triggers\dt *.*: List tables from all schemas (if *.* is omitted will only show SEARCH_PATH ones)\l: List databases\dn: List schemas\df: List functions\dv: List views\df+ __function : Show function SQL code.\x: Pretty-format query results instead of the not-so-useful ASCII tablessudo service postgresql stop
sudo service postgresql start
sudo service postgresql restart
sudo vim /etc/postgresql/9.3/main/postgresql.conf
# Uncomment/Change inside:
log_min_messages = debug5
log_min_error_statement = debug5
log_min_duration_statement = -1
sudo service postgresql restart
tail -f /var/log/postgresql/postgresql-9.3-main.log
postgresql.conf):log_line_prefix = '%t %u %d %a '
SELECT * FROM pg_proc WHERE proname='__procedurename__': List procedure/functionSELECT * FROM pg_views WHERE viewname='__viewname__';: List view (including the definition)SELECT pg_size_pretty(pg_total_relation_size('__table_name__'));: Show DB table space in useSELECT pg_size_pretty(pg_database_size('__database_name__'));: Show DB space in useshow statement_timeout;: Show current user's statement timeoutSELECT * FROM pg_indexes WHERE tablename='__table_name__' AND schemaname='__schema_name__';: Show table indexesSELECT
t.relname AS table_name,
i.relname AS index_name,
a.attname AS column_name
FROM
pg_class t,
pg_class i,
pg_index ix,
pg_attribute a,
pg_namespace n
WHERE
t.oid = ix.indrelid
AND i.oid = ix.indexrelid
AND a.attrelid = t.oid
AND a.attnum = ANY(ix.indkey)
AND t.relnamespace = n.oid
AND n.nspname = 'kartones'
ORDER BY
t.relname,
i.relname
SELECT datname, application_name, pid, backend_start, query_start, state_change, state, query
FROM pg_stat_activity
WHERE datname='__database_name__';
SELECT * FROM pg_stat_activity WHERE waiting='t'
SELECT pg_stat_get_backend_pid(s.backendid) AS procpid,
pg_stat_get_backend_activity(s.backendid) AS current_query
FROM (SELECT pg_stat_get_backend_idset() AS backendid) AS s;
Casting:
CAST (column AS type) or column::type'__table_name__'::regclass::oid: Get oid having a table nametop for PG. sudo apt-get install ptop + pg_top