Benito Serna Tips and tools for Ruby on Rails developers

What is an n+1 queries problem?

July 27, 2021

An n+1 queries problem means that a query is executed for every result of a previous query.

For example, with this records…

class Post < ActiveRecord::Base
  has_many :comments

class Comment < ActiveRecord::Base
  belongs_to :post

If you execute the next code…

Post.all.each do |post|
  post.comments.each do |comment|
    puts comment.body

You will execute…

If there are…

Related articles

No more… “Why active record is ignoring my includes?”

Get for free the first part of the ebook Fix n+1 queries on Rails that will help you:

  • Explain what is an n+1 queries problem
  • Identify when ActiveRecord will execute a query
  • Solve the latest comment example
  • Detect n+1 queries by watching the logs
  • Learn the tools to detect n+1 queries
Get the first part of the ebook for free