Drupal 7: Database Aggregate functions (SUM, MIN, MAX, COUNT, AVG,..)

The MySQL database query supports aggregate functions to retrieve values from the database. In our custom query, we can able to add aggregate queries. The function addExpression() takes object of database query to aggregate results in db_select(). The below example will demonstrate the usage of aggregate functions.



$query = db_select('node', 'n');
$query->addExpression('SUM(nid)', 'total');
$query->condition('n.type','article', '=');
$query->condition('n.status', 0, '=');
$result = $query->execute();
$result = $result->fetchField();
print $result;