How do I add an expression into a query? When I use the code below, I get the following error:


  Call to a member function addExpression() on a non-object


 $query = db_select('node', 'n')
    -&gt;fields('n', array('nid'))
    -&gt;execute()
    -&gt;fetchAssoc();
  $query-&gt;addExpression('MAX(nid)', 'max_nid');


What is wrong with that code?
Change the code to the following one.

$query = db_select('node', 'n');
$query-&gt;fields('n', array('nid'));
$query-&gt;addExpression('MAX(nid)', 'max_nid');
$query-&gt;execute()-&gt;fetchAssoc();


The value returned from fetchAssoc() is an array. Since you are assigning the value returned from fetchAssoc() to $query, and then calling $query-&gt;addExpression(), you rightly get the error. You cannot call a method on something that is not an object (in this case, an array).

If you want to list all the node IDs and set max_nid to the maximum value, you can use the following code.

$query = db_select('node', 'n');
$query-&gt;fields('n', array('nid','type'));
$query-&gt;leftJoin('node', 'n1', 'n1.type = n.type');
$query-&gt;addExpression('MAX(n1.nid)', 'max_nid');
$query-&gt;groupBy('n.nid');
$result = $query-&gt;execute()-&gt;fetchAll();4