PHP › Performance Optimization & OPcache
How does the N plus one query problem impact performance, and what general strategies help identify and fix this common performance issue?
IntermediateAnswer
The N plus one query problem occurs when code retrieves a list of records and then executes an additional separate query for each individual record's related data within a loop, resulting in a number of database queries proportional to the number of records rather than a small, fixed number, and this is typically identified by monitoring the actual number of queries executed for a given page and fixed by using eager loading or a single combined query to retrieve all necessary data upfront instead.
// Problematic: N+1 queries
foreach ($orders as $order) {
echo $order->customer->name; // separate query per order
}
// Better: single eager loaded query
$orders = Order::with('customer')->get();Real-world example A dashboard displaying one hundred orders along with each customer's name discovers, through a query logging tool, that it was executing one hundred and one separate database queries, and fixes the issue by switching to eager loading, reducing it down to just two total queries.