In my custom module for Drupal 8, I am using the following code.

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

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

foreach ($result as $row) {

Is there a way to get the number of rows with a function / class method?

$query = $this->connection->select('node_field_data', 'nf_data');
$result = $query->execute();
$records = $result->fetchAll();
$num_results = count($records);

This will leave you with $records being an array of all records and $num_results being the count of that array.

See: https://www.drupal.org/docs/8/api/database-api/result-sets

Also: Select documentation and StatementInterface (the return val of $query->execute) documentation

You may want to look into using entity queries, though I'm not sure what your goal is.


Use $query->countQuery()->execute()->fetchField(); This is fast.

See detail example.

$number = $this->connection->select(static::TABLE_NAME, 'f')
    ->condition('event', $name)
    ->condition('identifier', $identifier)
    ->condition('timestamp', REQUEST_TIME - $window, '>')
  • Yes, this is a better way.
    – apaderno
    May 16 '19 at 20:55
  • 1
    This is better if you don't actually want the results, you only want the count
    – sonfd
    Dec 16 '20 at 14:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.