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?

2 Answers 2


$query->countQuery()->execute()->fetchField() is faster.

$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
    Commented May 16, 2019 at 20:55
  • 1
    This is better if you don't actually want the results, you only want the count
    – sonfd
    Commented Dec 16, 2020 at 14:50
$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.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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