In Drupal 8 we can not use the rowCount property anymore in case of a select statement. Is there an elegant alternative?

I can use a foreach, but when converting from Drupal 7 I would like to replace the result->rowCount() more elegantly


According to the Drupal API, "in D8 rowCount() is the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed or throws \Drupal\Core\Database\RowCountException if the last executed statement was SELECT."

If you need to select count of rows you can use $query->addExpression('COUNT(*)');

   $query = \Drupal::database()->select('table', 't');
   $count = $query->execute()->fetchField();

You can try this:

$query = db_select('node', 'n')->fields('n', ['nid'])->execute();
$query->allowRowCount = TRUE;
$count = $query->rowCount();


$query = db_query('Select * from node');
$query->allowRowCount = TRUE;
$count = $query->rowCount();

Note: db_select() and db_query() are marked as deprecated, will be removed in Drupal 9.0.0. Instead, get a database connection injected into your service from the container and call select() or query() on it.

  • Are you sure this works for Drupal 8 db_select? I never got it to work. Александр Афанасьев worked for me. – Parag Jun 14 '17 at 16:44

rowCount() is supported for DELETE, INSERT, or UPDATE statements performed with structured query builders only, since they would not be portable across database engines otherwise


Setting the allowRowCount property to TRUE is not a good way to solve this issue.

A better way to do this is to use the built in countQuery:

$query = db_select('node', 'n')->fields('n', ['nid']);
if ($query->countQuery()->execute()->fetchField()) {
  $result = $query->execute();
  • I edited the code, since $query->countQuery() is a method, not a property. Also, it should be pointed out the if() statement is not necessary, if I just want to count the number of rows the query would select. – kiamlaluno Jan 25 '18 at 17:08

This is how I did it:

$database = \Drupal::database();
$query = $database->select('node__field_node_url', 'nnu');
$query->addField('nnu', 'entity_id');
$query->condition('nnu.field_node_url_uri', "entity:node/" . $article->entity_id);
$results = $query->execute()->fetchAll();
$count = count($results);

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.