</>

SQL Cheat Sheet

Practical SQL cheat sheet with setup steps, core workflows, debugging, and copy-paste examples.

sql queries schema performance

SQL cheat sheet with real commands and snippets for setup, core workflows, debugging, and production-safe automation patterns. If you are working across tools, pair this with the MySQL Cheat Sheet and Elasticsearch Cheat Sheet.

Setup and Connection

Goal: Connect to database shell or endpoint

# Run connection or version command
sqlite3 dev.db

# Run connection or version command
psql "$DATABASE_URL"

# Run connection or version command
mysql -u root -p

Schema and Data Modeling

Goal: Create a table/index/schema foundation

-- Create normalized tables with explicit constraints
CREATE TABLE users (
  id INTEGER PRIMARY KEY,
  email TEXT NOT NULL UNIQUE,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Core Queries and Mutations

Goal: Run practical read/write operations

-- Join users and orders and sort by recency
SELECT u.email, o.total, o.created_at
FROM users u
JOIN orders o ON o.user_id = u.id
ORDER BY o.created_at DESC
LIMIT 20;

Performance and Optimization

Goal: Add indexes and inspect query plans

-- Add supporting indexes and inspect query plan
CREATE INDEX idx_orders_user_id ON orders(user_id);
CREATE INDEX idx_orders_created_at ON orders(created_at DESC);
EXPLAIN SELECT * FROM orders WHERE user_id = 42 ORDER BY created_at DESC;

Automation and Backups

Goal: Create backup and restore routines

# Export data snapshot before risky migrations
pg_dump "$DATABASE_URL" > backup.sql || mysqldump appdb > backup.sql || true

# Compress backup artifact for storage
gzip -f backup.sql || true

# Verify backup file exists and has content
ls -lh backup.sql.gz || ls -lh backup.sql

Debugging and Troubleshooting

Goal: Inspect slow-query symptoms

# Check active connections/sessions
psql -c "SELECT now();" || mysql -e "SELECT NOW();" || true

# Inspect query plans for heavy statements
psql -c "EXPLAIN SELECT 1;" || mysql -e "EXPLAIN SELECT 1;" || true

# Search migration files for destructive statements
rg "DROP TABLE|TRUNCATE|DELETE FROM" prisma migrations sql -n

Common Gotchas

  • Use transactions for multi-step SQL data changes that must stay consistent.
  • Create indexes for frequent WHERE and JOIN columns, then verify with query plans.
  • Back up production data before schema migrations.
  • Separate read-only credentials from write credentials in app environments.
  • Monitor connection pool limits to avoid timeout spikes under load.

Related Cheat Sheets