HomeToolsAbout

N+1

What is it

It is much faster to issue 1 query that returns 100 results than to issue 100 queries that each return 1 result.

Solution

Typically be avoided by doing a join in your query to force-fetch all the data you need in one go.

Illustration

# N+1 Queries for 4 matching records (1+4 = 5 queries total) SELECT pc.id AS id, pc.review AS review, pc.post_id AS postId FROM post_comment pc SELECT p.title FROM post p WHERE p.id = 1 SELECT p.title FROM post p WHERE p.id = 2 SELECT p.title FROM post p WHERE p.id = 3 SELECT p.title FROM post p WHERE p.id = 4 # Extract all the data you need in the SQL query at once (1 query) SELECT pc.id AS id, pc.review AS review, p.title AS postTitle FROM post_comment pc JOIN post p ON pc.post_id = p.id
AboutContact