Load related rows without N+1 queries in an ORM

8 steps · about 2 h 20 min · Intermediate

  1. Log every SQL statement your app sends (reference, SQLAlchemy, 10 min)

    Turn on echo and logging to see repeated per-row queries.

  2. Choose lazy, joined or selectin loading (reference, SQLAlchemy, 25 min)

    The core guide to relationship loading strategies and raiseload.

  3. Write ORM selects with explicit joins (reference, SQLAlchemy, 20 min)

    Shows joins and options that fetch related rows in one round trip.

  4. Optimise Django database access (article, Django, 20 min)

    Checklist of query counting, select_related and bulk work.

  5. Use select_related and prefetch_related (reference, Django, 20 min)

    Exact semantics of the two Django eager-loading methods.

  6. Count queries per page with Debug Toolbar (repo, GitHub, 10 min)

    Makes duplicate queries visible during development.

  7. Eager load associations in Active Record (article, Rails Guides, 20 min)

    Shows includes, preload and strict_loading against N+1.

  8. Fix N+1 queries in Prisma (article, Prisma, 15 min)

    Same problem in a TypeScript ORM with include and batching.