Sort the entity obtained from the Query class with values from the Statistics module I am using the following code to sort the published nodes basing on the value stored from the Statistics module.

$query = \Drupal::entityQuery('node')
      -&gt;condition('status', 1)
      -&gt;range(0, 5)
      -&gt;sort('totalcount', 'DESC' );

$result = $query-&gt;execute();


The code is causing the following exception.


  Drupal\Core\Entity\Query\QueryException: 'totalcount' not found in Drupal\Core\Entity\Query\Sql\Tables->ensureEntityTable() (line 316 of core/lib/Drupal/Core/Entity/Query/Sql/Tables.php).


How do I sort nodes basing on the totalcount value stored from the Statistics module?
The code you are showing doesn't work because totalcount is not a property set for the node entity. That is a value saved in a different database table, not used from the node entity. See statistics_get(), which retrieves the value you are looking for.

  if ($nid &gt; 0) {
    // Retrieve an array with both totalcount and daycount.
    return db_query('SELECT totalcount, daycount, timestamp FROM {node_counter} WHERE nid = :nid', array(':nid' =&gt; $nid), array('target' =&gt; 'replica'))-&gt;fetchAssoc();
  }


Since the entity query doesn't allow to join tables, you need to:


Add a tag to the entity query you are using
Implement hook_query_TAG_alter() to alter the queries with the tag you added (Replace TAG with the tag you added to the entity query)


node_query_node_access_alter() is the implementation of that hook done from the Node module to allow an entity query to return just the nodes the currently logged-in user has access. You can use its code as guide to write your own implementation.

For example, I would start trying with the following code.

$query = \Drupal::entityQuery('node')
  -&gt;addTag('statistics_totalcount')
  -&gt;condition('status', 1)
  -&gt;range(0, 5)
  -&gt;sort('totalcount', 'DESC');

$result = $query-&gt;execute();

function mymodule_query_stastics_totalcount_alter(Drupal\Core\Database\Query\AlterableInterface $query) {
  $query-&gt;join('node_counter', 'nc', '%alias.nid = n.nid');
}