Expressions
The Select query builder supports using expressions in the field list. Example expressions include "double the age field," "count of all name fields," and a substring of the title field. Note that many expressions may use SQL functions, and not all SQL functions are standardized across all databases. Module developers must ensure that only expressions compatible with supported databases are used. (See List of functions and operators)
To add an expression to a query, use the addExpression() method.
$count_alias = $query->addExpression('COUNT(uid)', 'uid_count'); $count_alias = $query->addExpression('created - :offset', 'timestamp', array(':offset' => 3600));
The first line above adds "COUNT(uid) AS uid_count" to the query. The second parameter is the alias for the field. In the rare case where the alias is already in use, a new one will be generated, and the return value of addExpression() will be the usable alias. If no alias is provided, a default value of "expression" (or expression_2, expression_3, etc.) will be generated.
The optional third parameter is an associative array of placeholder values used as part of the expression.
Note that some SQL expressions may not function properly unless accompanied by a GROUP BY clause added via $query->groupBy(). Developers should ensure the generated query is valid.