Keith Schacht’s Weblog

Subscribe

📄 Query optimization in rails

14th April 2025

It’s been awhile since I’ve gone deep on optimizing queries in rails. Over the years I’ve settled into two default approaches: (1) drop into raw SQL and write CTEs that help get a clean set of the final activerecord objects I’m looking for, or (2) add various cache columns to tables such as last_comment_id to greatly simplify the SQL.

I came across this discussion online that did a great job of surveying a whole range of approaches including some new ones I have never tried. This article offered a great summary of the options and I learned Rails now supports CTEs natively.

More recent articles

This is Query optimization in rails by Keith Schacht, posted on 14th April 2025.

Next: React in Rails is gaining momentum with Inertia

Previous: Ruby's clamp method reduces conditionals