Optimizing SQL Queries in Rails: Real Examples from Production
At some point in my career, I hit the classic problem: everything worked fine in development, but once real data came in, the app slowed down. The culprit? Inefficient SQL queries.
Rails makes it easy to query the database, but it’s also easy to write code that looks fine yet performs poorly. Here are some real lessons from production.
The N+1 Query Problem
Example (Bad)
This triggers 1 query for users + 1 query per user = N+1 queries.
Fix (Good)
Now, Rails loads all posts in two queries total.
Selecting Only What You Need
Example (Bad)
This loads entire rows, even columns we don’t need.
Fix (Good)
Lighter queries = faster performance.
Using Indexes
Example (Bad)
Without an index on email, this scans the entire table.
Batching Large Queries
Example (Bad)
This loads all users into memory.
Fix (Good)
Memory stays low, queries are batched.
Measuring Queries
Use Rails logging or bullet gem to spot N+1 queries:
It warns you when eager loading is missing.
Optimizing SQL in Rails isn’t about writing raw queries — it’s about being mindful of how ActiveRecord works. The three biggest wins I’ve seen in real projects were:
Fixing N+1 queries
Adding the right indexes
Batching data loads
Once I applied these consistently, page load times dropped from seconds to milliseconds — a real turning point in my growth as a backend engineer.