This article was originally published on bmf-tech.com.
Overview
A summary of the N+1 problem and how to address it.
What is the N+1 Problem
- The issue where 1 SQL query is issued for retrieving all records plus N SQL queries for each record.
- It is easier to understand if interpreted as 1+N rather than N+1.
Example
- Case of retrieving data for list display
- Issue 1 SELECT query to retrieve all data for the list (returns N records)
- Issue N SELECT queries to retrieve related data for N records
Solutions
- Join
SELECT "users".* FROM "users" INNER JOIN "posts" ON "posts"."user_id" = "users"."id" WHERE "posts"."id" = 1- Eager Loading
SELECT "users".* FROM "users"SELECT "posts".* FROM "posts" WHERE "posts"."id" IN (1, 2, 3, 4, 5)
Top comments (0)