PostgreSQL cheat sheet
psql’s backslash commands, plus the queries you need when the database is slow: what’s running, what’s blocked, what’s big, and which indexes aren’t pulling their weight.
In Snippet Keeper, click Import at the bottom of the sidebar and choose the file. They land in your psql app, and ones you already have are skipped. The highlighted parts become fill-in fields: type a value (or pick one), and the finished command is on your clipboard.
Connecting
psql -h host -p port -U user -d database
psql "postgresql://user@host:port/database"
psql -d database -c "query"
psql -d database -f file
psql commands
\l
\c database
\dt
\dt schema.*
\d+ table
\du
\dn
\x auto
\timing
\e
\copy (query) TO 'file' WITH CSV HEADER
Sizes
SELECT relname AS table, pg_size_pretty(pg_total_relation_size(relid)) AS size
FROM pg_catalog.pg_statio_user_tables
ORDER BY pg_total_relation_size(relid) DESC
LIMIT limit;
SELECT pg_size_pretty(pg_database_size('database'));
SELECT reltuples::bigint AS estimate FROM pg_class WHERE relname = 'table';
Performance
SELECT pid, now() - query_start AS duration, state, query
FROM pg_stat_activity
WHERE state <> 'idle'
ORDER BY duration DESC;
SELECT pid, pg_blocking_pids(pid) AS blocked_by, query
FROM pg_stat_activity
WHERE cardinality(pg_blocking_pids(pid)) > 0;
SELECT pg_cancel_backend(pid);
SELECT pg_terminate_backend(pid);
EXPLAIN (ANALYZE, BUFFERS) query;
SELECT relname AS table, indexrelname AS index, pg_size_pretty(pg_relation_size(indexrelid)) AS size
FROM pg_stat_user_indexes
WHERE idx_scan = 0
ORDER BY pg_relation_size(indexrelid) DESC;
CREATE INDEX CONCURRENTLY index_name ON table (column);
Exploring data
SELECT column_name, data_type, is_nullable
FROM information_schema.columns
WHERE table_name = 'table'
ORDER BY ordinal_position;
SELECT column, count(*)
FROM table
GROUP BY column
HAVING count(*) > 1
ORDER BY count(*) DESC;
Roles
CREATE ROLE user WITH LOGIN PASSWORD 'password';
GRANT USAGE ON SCHEMA schema TO user;
GRANT SELECT ON ALL TABLES IN SCHEMA schema TO user;
ALTER DEFAULT PRIVILEGES IN SCHEMA schema GRANT SELECT ON TABLES TO user;
Backup and restore
pg_dump -Fc -d database -f file
pg_restore --no-owner -d database file
pg_dump -d database -t table -f table.sql
Keep these one keystroke away.
Snippet Keeper is a Mac app for the commands you keep looking up. Press ⌥⇧Space in any app, type a few letters, fill in the blanks, and it’s on your clipboard.