Overview
This article summarizes the explanation and response to the N+1 problem.
What is the N+1 Problem?
- A problem where N SQL statements are issued to retrieve all records, resulting in 1 + N SQL statements.
- It is easier to interpret as 1 + N rather than N + 1.
Example
- A case of retrieving data for display
- Issue a SELECT statement once to retrieve all data for the list (returning N records).
- Issue N SELECT statements to retrieve related data for the N records.
Response
- 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)
References
- The N+1 Problem is the 1+N Problem
- N+1 Problem
What is the N+1 Problem / Eager Loading- Differences between ActiveRecord's joins, preload, includes, and eager_load