# Why your database is slow and it's probably the N+1

Somebody on the team asks this once a month so here it is written down.

You have a page that lists 50 blog posts and each post shows its author's name. In the ORM you write `posts = Post.all` and then in the template you do `post.author.name` for each one. Feels clean. It is not clean. That template just ran 51 queries: one to get the posts, then one more per post to go fetch the author, fifty times. This is the N+1. N posts, plus 1. It's the single most common reason a page that was fast with your 12 test rows falls over with 12,000 real ones.

The fix is to tell the ORM up front that you're going to want the authors, so it can grab them in one shot with a second query (or a join). In Rails that's `Post.includes(:author)`. In Django it's `select_related`. In raw SQL it's just... writing the join you should have written. The names differ, the idea is identical: load the related rows in bulk instead of one at a time.

How do you find these? Turn on query logging in development and watch the count while you load a page. If clicking one page fires 200 queries, you have an N+1 somewhere, guaranteed. There are gems and middleware (bullet, for Rails) that will scream at you when they detect one. Use them.

One caveat people get wrong: eager loading isn't free. If you `includes` a table you don't end up using, you did extra work for nothing. And if the association is huge, pulling it all into memory can be worse than the N+1 was. Measure. The whole point is that you looked at the query count instead of guessing.
