Most slow queries have one of three causes: missing indexes, fetching too many rows, or N+1 query patterns.
Always start here. Never guess.
EXPLAIN ANALYZE
SELECT * FROM blogs
WHERE user_id = 42
ORDER BY created_at DESC;
Look for Seq Scan on large tables — that's your first target.
CREATE INDEX idx_blogs_user_id ON blogs(user_id);
CREATE INDEX idx_blogs_created_at ON blogs(created_at DESC);
Fetch only the columns you need. On wide tables this makes a significant difference.
If you're running one query per item in a list, you have an N+1 problem. Use JOINs or batch fetching instead.
EXPLAIN ANALYZE should be required reading for every backend dev. So many people skip this step.
The N+1 section is so important. I see this mistake constantly in code reviews.
Log in to leave a comment.