The N+1 Query Problem

The N+1 Query Problem

Why 20 posts become 21 queries, and how to fix it with a join

What you'll learn

  • Why a query inside a loop is slow
  • How ORMs hide extra queries
  • Fixing it with a JOIN or WHERE id IN
  • Eager loading, and spotting N+1 in your logs

In this video, we'll look at why a page showing 20 blog posts can end up running 21 database queries. We'll cover what the N+1 query problem is, why running a query inside a loop adds up, and how ORMs hide it from you.

We'll also cover fixing it with a SQL join, batching with WHERE id IN, and eager loading in ORMs like Prisma and Rails.

By the end, you'll know how to spot N+1 queries in your query logs and how to fix them.

More videos

32 short explainers so far, with more on the way

View all videos

Join the Community

roadmap.sh is among the top 10 most starred projects on GitHub and is visited by hundreds of thousands of developers every month.

Top 10 out of 28M!

371K

GitHub Stars

Star us on GitHub
Help us reach #1

+90kevery month

+3.2M

Registered Users

Register yourself
Commit to your growth

+2kevery month

52K

Discord Members

Join on Discord
Join the community

RoadmapsGuidesFAQsYouTube

roadmap.shby@nilbuild

Community created roadmaps, best practices, projects, articles, resources and journeys to help you choose your path and grow in your career.

© roadmap.sh·Terms·Privacy·

ThewNewStack

The top DevOps resource for Kubernetes, cloud-native computing, and large-scale development and deployment.