How do I get the number of rows selected from the query? In my custom module for Drupal 8, I am using the following code.

$query = $this-&gt;connection-&gt;select('node_field_data', 'nf_data');
$result = $query-&gt;execute();


I can get the number of rows looping over $result.

foreach ($result as $row) {
  $num++;
}


Is there a way to get the number of rows with a function / class method?
Use $query->countQuery()->execute()->fetchField(); This is fast.

See detail example.

$number = $this-&gt;connection-&gt;select(static::TABLE_NAME, 'f')
    -&gt;condition('event', $name)
    -&gt;condition('identifier', $identifier)
    -&gt;condition('timestamp', REQUEST_TIME - $window, '&gt;')
    -&gt;countQuery()
    -&gt;execute()
    -&gt;fetchField();