0
0
Ruby on Railsframework~8 mins

Raw SQL when needed in Ruby on Rails - Performance & Optimization

Choose your learning style9 modes available
Performance: Raw SQL when needed
MEDIUM IMPACT
This affects database query speed and server response time, impacting how fast data loads on the page.
Fetching complex data with many joins or conditions
Ruby on Rails
User.find_by_sql("SELECT users.*, posts.title FROM users JOIN posts ON posts.user_id = users.id WHERE posts.published = TRUE")
Raw SQL runs a single optimized query directly on the database.
📈 Performance Gainreduces query time by 50-70%, speeds up LCP
Fetching complex data with many joins or conditions
Ruby on Rails
User.joins(:posts).where(posts: { published: true }).select('users.*, posts.title').to_a
ORM generates inefficient SQL causing slow database response.
📉 Performance Costblocks rendering for 100-300ms on complex queries
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
ORM complex queriesN/A (server-side)N/AHigher due to delayed HTML[X] Bad
Raw SQL optimized queriesN/A (server-side)N/ALower due to faster HTML[OK] Good
Rendering Pipeline
Raw SQL affects the server-side data fetching stage before HTML is sent to the browser. Faster queries mean faster HTML generation and quicker first paint.
Data Fetching
Server Response
HTML Rendering
⚠️ BottleneckData Fetching (database query execution)
Core Web Vital Affected
LCP
This affects database query speed and server response time, impacting how fast data loads on the page.
Optimization Tips
1Use raw SQL only for complex queries where ORM is slow.
2Measure query time before switching to raw SQL.
3Keep raw SQL readable and well-documented.
Performance Quiz - 3 Questions
Test your performance knowledge
Why might raw SQL improve page load speed compared to ORM queries?
AIt runs a single optimized query directly on the database.
BIt reduces the number of DOM nodes created.
CIt decreases CSS selector complexity.
DIt avoids JavaScript parsing.
DevTools: Network
How to check: Open DevTools, go to Network tab, reload page, and check the time for the main document request.
What to look for: Look for shorter server response time indicating faster database queries and HTML generation.