Back to Cheatsheets
Databases Cheatsheet
Essential database commands, concepts, and best practices for MongoDB, PostgreSQL, Redis, and more.
MongoDB
mongoshStart MongoDB shell
db.collection.find()Find all documents
db.collection.insertOne({ field: 'value' })Insert one document
db.collection.updateOne({ _id: id }, { $set: { field: 'value' } })Update one document
db.collection.deleteOne({ _id: id })Delete one document
PostgreSQL
psql -U username -d databaseConnect to database
\lList databases
\dtList tables
\d table_nameDescribe table
\qQuit psql
Redis
redis-cliStart Redis CLI
SET key valueSet key-value pair
GET keyGet value by key
DEL keyDelete key
KEYS *List all keys
Database Design
CREATE TABLE users (id SERIAL PRIMARY KEY, name VARCHAR(100))Create table with primary key
ALTER TABLE users ADD COLUMN email VARCHAR(255) UNIQUEAdd unique column
CREATE INDEX idx_name ON users(name)Create index
CREATE TABLE orders (id SERIAL PRIMARY KEY, user_id INTEGER REFERENCES users(id))Create table with foreign key
CREATE VIEW user_orders AS SELECT * FROM users JOIN orders ON users.id = orders.user_idCreate view
Database Maintenance
VACUUM ANALYZE table_nameVacuum and analyze table
REINDEX DATABASE database_nameRebuild all indexes
pg_dump database_name > backup.sqlCreate database backup
psql database_name < backup.sqlRestore from backup
ANALYZE table_nameUpdate statistics
Performance
EXPLAIN SELECT * FROM tableShow query plan
EXPLAIN ANALYZE SELECT * FROM tableShow query execution time
SELECT pg_size_pretty(pg_total_relation_size('table_name'))Show table size
SELECT * FROM pg_stat_activityShow active queries
SELECT * FROM pg_stat_user_tablesShow table statistics