How to sort the query results? In my task I need to display the results based on "the newest first". I perform a query: 

$query = \Drupal::database()-&gt;select('node_field_data', 'node');
$query-&gt;innerJoin('node__field_ils_apps', 'app', 'app.entity_id = node.nid AND app.field_ils_apps_target_id = '.$node-&gt;id());
$query-&gt;addField('app', 'entity_id', 'nid');
$query-&gt;groupBy('app.entity_id');

$query-&gt;orderBy('created', 'DESC');
$query-&gt;execute();


But it returns me an error: 

SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #1 of ORDER BY clause is not in GROUP BY clause and contains nonaggregated column 


Could you please tell me what I do wrong?
Try this out 

use Drupal\Core\Database\Database;

$connection = Database::getConnection();
  //- Step one get all referenced nids
  $query = $connection-&gt;select('node_field_data', 'nfd')
    -&gt;fields('nfd', ['nid', 'created']);
   $query-&gt;innerJoin('node__field_ils_apps', 'app', 'nfd.nid = app.entity_id');
  $query-&gt;orderBy('created', 'DESC');
  $result = $query-&gt;execute()-&gt;fetchAll(PDO::FETCH_ASSOC);