Databases
PostgreSQL Admin Cheat Sheet
psql commands and queries for running PostgreSQL: roles and grants, sizes, active queries and locks, sequences, vacuum, config, backup and restore.
Updated November 1, 2026 · Applies to PostgreSQL 14–18
Connect
sudo -u postgres psql # local admin loginpsql -h db.internal -U app -d shop # remotepsql "postgresql://app@db.internal:5432/shop?sslmode=require"psql commands
\conninfo who and where am I\l databases\c shop switch database\dn schemas\dt tables \dt+ with sizes\d orders columns, indexes, constraints\du roles\dp orders privileges on a table\x auto wide rows vertically\timing on show query time\i file.sql run a file\q quitRoles & privileges
CREATE ROLE app LOGIN PASSWORD 'change-me';GRANT CONNECT ON DATABASE shop TO app;GRANT USAGE ON SCHEMA public TO app;GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO app;GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO app;-- tables created later, by the role that runs this:ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO app;ALTER ROLE app PASSWORD 'new-password';Guide: Permission denied for table
Sizes
SELECT pg_size_pretty(pg_database_size(current_database()));
SELECT relname, pg_size_pretty(pg_total_relation_size(relid)) AS totalFROM pg_stat_user_tablesORDER BY pg_total_relation_size(relid) DESCLIMIT 10;Active queries & locks
SELECT pid, usename, state, now() - query_start AS runtime, left(query, 60) AS queryFROM pg_stat_activityWHERE state <> 'idle'ORDER BY runtime DESC NULLS LAST;
-- who is waiting for whomSELECT pid, pg_blocking_pids(pid) AS blocked_by, left(query, 60)FROM pg_stat_activityWHERE cardinality(pg_blocking_pids(pid)) > 0;
SELECT pg_cancel_backend(12345); -- cancel the querySELECT pg_terminate_backend(12345); -- end the sessionSequences
-- after an import: next id = max(id) + 1SELECT setval(pg_get_serial_sequence('orders', 'id'), COALESCE(MAX(id), 0) + 1, false)FROM orders;Guide: Duplicate key / sequence out of sync
Vacuum & statistics
SELECT relname, n_live_tup, n_dead_tup, last_autovacuumFROM pg_stat_user_tablesORDER BY n_dead_tup DESCLIMIT 10;
VACUUM (ANALYZE, VERBOSE) orders;ANALYZE; -- refresh planner statsConfiguration
SHOW config_file;SHOW hba_file; -- who may connect, and howSHOW max_connections;ALTER SYSTEM SET work_mem = '64MB'; -- written to postgresql.auto.confSELECT pg_reload_conf(); -- apply without restartSELECT name, setting, pending_restartFROM pg_settings WHERE pending_restart;Backup & restore
pg_dump -Fc -d shop -f shop.dump # one database, custom formatpg_restore -d shop_copy shop.dump # into an existing databasepg_restore -l shop.dump # list what's insidepg_dump -d shop -f shop.sql # plain SQLpsql -d shop_copy -f shop.sqlpg_dumpall --globals-only -f roles.sql # roles (not in pg_dump)Warning
A backup you never restored is a hope, not a backup. Restore into a test database from time to time.