Today I Learned

hashrocket A Hashrocket project

Run Explain (and Anaylze) in Rails Console

If you're troubleshooting some slow SQL queries, chances are you've used EXPLAIN or even EXPLAIN ANALYZE. But TIL, that you can actually run these in the Rails console on your Rails models (Active Model Relations). It looks something like this -

> User.active.explain

Or if you're on a more recent version of Rails, you can also pass arguments to .explain, such as :analyze -

> User.active.explain(:analyze)

You can also call it on other methods like pluck, etc. -

> User.active.explain.pluck

Be warned that calling .explain will execute the query.

https://devdocs.io/rails~7.2/activerecord/relation#method-i-explain

https://guides.rubyonrails.org/active_record_querying.html#running-explain

See More #rails TILs
Looking for help? Hashrocket has been an industry leader in Ruby on Rails since 2008. Rails is a core skill for each developer at Hashrocket, and we'd love to take a look at your project. Contact us and find out how we can help you.