Can I only traverse a DatabaseConnection object once? I have a database query result, and I want to go through the records twice. However, the second time I go through it, nothing happens. It seems you can only iterate through this object once?

My code looks like this:

$query = db_select( ... );
$result = $query-&gt;execute();
if ( $result-&gt;rowCount() &gt; 0 ) {
  foreach ( $result as $record ) {
    ... processing happens here
  }
}

// now loop through again, to mark records as processed, upon success.
foreach ( $result as $record ) {
  ... additional processing here
}


And the additional processing doesn't happen. 

As a work around, I added $records = $result-&gt;fetchAllKeyed(); before the initial processing, and then the result object had no records! 

I found nothing in the documentation about resetting the object or anything. 

Is this how the object works? Can I reset the iterator again, or must I fetch the keys initially to have an array that I can iterate over many times?
This is expected behaviour; Drupal wraps around PDO and this is how PDO query functions behave also. Have a look at Is it possible to rewind a PDO result for a more in-depth discussion.

The standard way to get around this would be to use either fetchAllKeyed() as you've mentioned, or fetchAll() instead. The latter will produce an array of object results that can be iterated over as many times as you want.

$query = db_select( ... );
$result = $query-&gt;execute();
if ( $result-&gt;rowCount() &gt; 0 ) {
  $data = $result-&gt;fetchAll();

  foreach ($data as $item) {
    // do something with data
  }

  foreach ($data as $item) {
    // do something with data again
  }
}