MohitDecodes
Back to blogsBackend

Database Indexing & Fixing the N+1 Query Problem in ORMs

October 12, 2026 · 7 min read

ORMs like Django ORM, SQLAlchemy, Mongoose, and Prisma make querying databases effortless — and make it effortless to accidentally fire 101 SQL queries for a single page.

Spot and fix the N+1 query trap

Fetching 50 blog posts in 1 query and then looping through each post to read `post.author.name` triggers 50 extra database round trips unless you eager-load the relation (`select_related` / `prefetch_related` in Django, `joinedload` in SQLAlchemy).

# N+1 queries
posts = Post.objects.all()

# 1 SQL JOIN query
posts = Post.objects.select_related("author").all()

Index the columns you actually filter and sort by

  • Add B-tree indexes on foreign keys, `email`, `slug`, and `(user_id, created_at)` composite filters.
  • Use `EXPLAIN ANALYZE` to confirm Postgres/MySQL uses an Index Scan instead of a Sequential Scan.
  • Avoid over-indexing write-heavy tables since every `INSERT`/`UPDATE` must update those indexes too.