DevOpsil
PostgreSQL37 commands

PostgreSQL Cheat Sheet

Essential PostgreSQL commands for databases, tables, queries, users, backups, and performance tuning.

Connection & psql

CommandDescription
psql -U postgres
Connect as postgres user
psql -h host -U user -d dbname
Connect to remote database
\l
List databases
\c dbname
Switch database
\dt
List tables in current schema
\d tablename
Describe table structure
\du
List roles/users
\q
Quit psql
\timing on
Show query execution time

Database Management

CommandDescription
CREATE DATABASE mydb;
Create database
DROP DATABASE mydb;
Delete database
ALTER DATABASE mydb RENAME TO newdb;
Rename database
CREATE SCHEMA api;
Create schema
SET search_path TO api, public;
Set schema search path

Tables & Indexes

CommandDescription
CREATE TABLE users (id SERIAL PRIMARY KEY, name TEXT NOT NULL);
Create table
ALTER TABLE users ADD COLUMN email TEXT UNIQUE;
Add column
ALTER TABLE users DROP COLUMN email;
Drop column
CREATE INDEX idx_users_email ON users(email);
Create index
CREATE INDEX CONCURRENTLY idx_name ON tbl(col);
Create index without locking
DROP INDEX idx_users_email;
Drop index
TRUNCATE TABLE users RESTART IDENTITY CASCADE;
Empty table and reset IDs

Users & Permissions

CommandDescription
CREATE USER appuser WITH PASSWORD 'secret';
Create user
ALTER USER appuser WITH SUPERUSER;
Grant superuser
GRANT ALL ON DATABASE mydb TO appuser;
Grant database access
GRANT SELECT, INSERT ON ALL TABLES IN SCHEMA public TO appuser;
Grant table privileges
REVOKE ALL ON DATABASE mydb FROM appuser;
Revoke access

Backup & Restore

CommandDescription
pg_dump mydb > backup.sql
Dump database to SQL
pg_dump -Fc mydb > backup.dump
Dump in custom format
pg_restore -d mydb backup.dump
Restore from dump
psql mydb < backup.sql
Restore from SQL file
pg_dumpall > all_databases.sql
Dump all databases

Performance

CommandDescription
EXPLAIN ANALYZE SELECT ...;
Show query plan with timing
SELECT pg_size_pretty(pg_database_size('mydb'));
Database size
SELECT * FROM pg_stat_activity;
Active connections/queries
SELECT pg_cancel_backend(pid);
Cancel running query
SELECT pg_terminate_backend(pid);
Kill connection
VACUUM ANALYZE tablename;
Reclaim space and update stats