Add a MAX aggregation function to a query I'm building a query with $query = new db_select('node', 'n') and I'm grouping by a certain field (let's say $query-&gt;groupBy('title')), when I'm aggregate another field (such as $query-&gt;addField('n', 'MAX(nid)')) it gets sanitized into a field called n.MAXnid (which crashes with a warning when executed)

How can I add a n.MAX(nid) field to my select query?
In your case, the code should be something similar to the following one:

$query = db_select('node', 'n')-&gt;groupBy('title');
$query-&gt;addExpression('MAX(nid)', 'max_nid');


You don't use $query = new db_select('node', 'n'); db_select() already returns an object. If you want to clone that object, you should not invoke new on it.

$query->addExpression() returns the alias currently used for the expression you add; it is normally the same alias passed to the method, but it can be different if the alias is already used. In this case, the alias is max_nid if max_nid is not already used, or max_nid_N if the alias is already used; N is an integer that is added to make the alias unique.
Using the alias returned from $query-&gt;addExpression() is important when a function is altering a query passed from other functions, such as in the case of a query passed to a hook. In this specific case it is not necessary, as the function that is calling db_select() is also adding the expression.