PDO::fetchAll vs. PDO::fetch in a loop

PDO::fetchAll vs. PDO::fetch in a loop

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

PDO::fetchAll vs. PDO::fetch in a Loop

There is no inherent performance difference between PDO::fetchAll() and looping through PDO::fetch() when fetching data into user-defined classes, provided you are using standard row-by-row retrieval. The initial assumption that fetchAll() might be faster because it executes multiple operations in a single statement is incorrect for the specific context of hydration into objects.

When you use PDO::fetch(), PDO retrieves one row at a time from the database cursor and hands control back to PHP, where your application logic processes that single row. When you use PDO::fetchAll(), PDO continues to pull rows from the same underlying cursor internally until the result set is exhausted, returning them all as an array in a single call.

The critical distinction lies entirely in where the iteration happens and how memory is managed, not in the speed of the network round-trip or database query execution. Both methods rely on the server-side fetch_mode (defaulting to PDO::FETCH_ASSOC unless configured otherwise) to stream data from the driver to the PHP process. If you are fetching into objects using a mode like PDO::FETCH_OBJ or by mapping columns via PDO::FETCH_CLASS, the overhead of object instantiation occurs in PHP regardless of whether PDO calls it once for an array or repeatedly inside a loop.

Memory and Resource Implications

The primary trade-off involves memory consumption rather than raw execution speed. With PDO::fetch(), you typically process rows immediately—perhaps inserting them into a queue, saving to cache, or iterating over a generator pattern. This approach keeps your working set small; you only hold one row in memory at any given time before processing it.

Conversely, PDO::fetchAll() loads the entire result set into an array structure before returning control to your script. If you are hydrating this entire array into objects, you are instantiating every object upfront. For large datasets, this can lead to significant memory spikes. In PHP 8.1+, the PDO::FETCH_LAZY mode allows for lazy hydration, but standard usage of fetchAll() combined with immediate class mapping will eagerly construct all objects simultaneously.

If your use case requires processing rows sequentially—for example, logging progress or breaking early based on a condition—fetch() is the superior architectural choice because it prevents holding unnecessary data in memory. If you need to iterate multiple times over the same data, fetchAll() is necessary, but you must ensure the database connection remains open and that the result set fits within your server's available RAM.

Implementation Patterns

Consider a scenario where you are fetching users for a bulk update operation:

// Pattern A: Fetching in a loop
$stmt = $pdo->query("SELECT * FROM users WHERE active = 1");
foreach ($stmt as $user) {
    // $user is an object here if using PDO::FETCH_CLASS
    $this->processUser($user);
}

// Pattern B: Fetching all at once
$stmt = $pdo->prepare("SELECT * FROM users WHERE active = 1");
$stmt->execute();
$users = $stmt->fetchAll(PDO::FETCH_CLASS, User::class);

foreach ($users as $user) {
    $this->processUser($user);
}

In the first pattern, PDO::fetch() is implicitly called by the foreach loop. The driver manages the cursor internally, and PHP processes rows one by one. In the second pattern, fetchAll() pulls everything into $users. While the database query execution time is identical in both cases, the memory profile differs drastically if $users contains thousands of objects.

When Does It Actually Matter?

Performance differences become relevant only when dealing with extremely large result sets where memory fragmentation becomes a bottleneck, or when the application architecture demands strict streaming behavior. In most standard web applications fetching hundreds or even a few thousand rows, the difference in execution time is negligible compared to database latency and object serialization overhead.

If you are working within the Laravel ecosystem, you might encounter similar patterns when querying Eloquent models. While Eloquent abstracts this away, understanding the underlying PDO behavior helps when optimizing raw queries or building custom repositories. The principle remains: choose fetch() for streaming and memory efficiency, and reserve fetchAll() for scenarios where random access to the full dataset is required.

For more details on optimizing database interactions in Laravel applications, you can refer to resources like https://laravelcompany.com.

Our network