To improve database performance by writing efficient SQL queries, using indexes correctly, and avoiding common pitfalls like N+1 problems.
- When an API endpoint is slow due to database latency.
- When reviewing database access patterns in code reviews.
- When dealing with large datasets.
- Analyze Query Plan: Use
EXPLAIN ANALYZE(Postgres) or equivalent to understand execution path. Look for "Seq Scan" on large tables. - Add Indexes:
- Index columns used in
WHERE,JOIN, andORDER BYclauses. - Use composite indexes for multi-column queries (order matters: equality first, then range).
- Index columns used in
- Optimize Selects:
- Select only necessary columns (
SELECT id, namevsSELECT *). - Avoid
SELECT *in production code.
- Select only necessary columns (
- Fix N+1 Problems:
- Use eager loading (
JOINor.withGraphFetched()in ORMs) instead of iterating and querying in a loop.
- Use eager loading (
- Refactor Complex Logic:
- Move complex data manipulation to the database (aggregations, window functions) if it reduces data transfer.
- Batch inserts/updates instead of one-by-one.
- Do not over-index (indexes slow down writes).
- Avoid functions on indexed columns in
WHEREclauses (prevents index usage). - Test performance with realistic data volumes.
Optimized SQL queries or ORM calls that execute significantly faster and consume fewer resources.