Optimize Database Queries
Use Indexes
# In migration
def up
create_index :users, :email, unique: true
create_index :posts, :user_id
create_index :posts, [:user_id, :created_at]
create_index :orders, :status
endAnalyze Query Plans
# PostgreSQL
AcmeDB.query("EXPLAIN ANALYZE SELECT * FROM users WHERE email = 'test@example.com'")
# Look for:
# - Sequential Scan (bad for large tables)
# - Index Scan (good)
# - Index Only Scan (best)Avoid N+1 Queries
The Problem
The Solution
Using Joins
Select Only Needed Columns
Use Batch Processing
Optimize COUNT Queries
Use Exists Instead of Count
Limit Result Sets
Use Database-Level Operations
Batch Updates
Batch Inserts
Use Prepared Statements
Connection Pooling
Query Caching
Use Read Replicas
Optimize Specific Patterns
Pagination
Search
Date Ranges
Monitor Query Performance
See Also
Last updated
Was this helpful?
