diff --git a/core/lib/Drupal/Core/Database/StatementPrefetch.php b/core/lib/Drupal/Core/Database/StatementPrefetch.php
index 58b48c69c38033d8ec8dca4615093b88a4d11449..e3d9dedacbc860da401551157a5b51dc3259c834 100644
--- a/core/lib/Drupal/Core/Database/StatementPrefetch.php
+++ b/core/lib/Drupal/Core/Database/StatementPrefetch.php
@@ -356,10 +356,17 @@ public function valid() {
     return isset($this->currentRow);
   }
 
-  /* Implementations of StatementInterface. */
-
+  /**
+   * {@inheritdoc}
+   */
   public function rowCount() {
-    return $this->rowCount;
+    // SELECT query should not use the method.
+    if ($this->allowRowCount) {
+      return $this->rowCount;
+    }
+    else {
+      throw new RowCountException();
+    }
   }
 
   public function fetch($fetch_style = NULL, $cursor_orientation = \PDO::FETCH_ORI_NEXT, $cursor_offset = NULL) {