Skip to content
Web Design & Development

The N+1 Query Problem, Done Properly

A database performance problem where code runs one query to load a list, then another query for each item, instead of loading related data together.

MediaScaleUp Editorial Team 2 min read 13 views
The N+1 Query Problem, Done Properly

The key figures

Pattern
one query for a list plus one per item
Fix
eager loading related data in fewer queries
Laravel
with() eager loads Eloquent relationships
Detection
query logs and profiling tools reveal repeated queries

Why this is worth getting right

N+1 queries are a very common cause of slow pages in applications that use ORMs, and they get worse as data grows.

Do this, not that

Do

  • Eager load relationships used in lists
  • Monitor query counts per request
  • Use profiling tools in development
  • Add tests or alerts for query counts on key pages
  • Paginate large lists

Don’t

  • Accessing relationships inside loops without eager loading
  • Loading unnecessary relationships
  • Ignoring query counts until production slows
  • Fixing symptoms with caching alone

When to bring in help

Our advice Bring in help when pages slow down as data grows.

Where this comes from

The figures and practices above come from the sources listed.

Working on something like this?

We take on Web Design & Development work for teams who want it done once, properly. Tell us what you are building and we will tell you honestly whether we are the right studio for it. Start a project.

Where to go next

Spotted something wrong? Report an error on this page. We correct on the page and say what changed.

All services

The work behind this article, and what it costs.

MediaScaleUp Editorial Team

Articles here are researched, written and checked by the MediaScaleUp studio team before they are published, and dated when they are reviewed.

Keep reading

More in Web Design & Development