7.x select.inc SelectQuery::countQuery()

Get the equivalent COUNT query of this query as a new query object.

Return value

SelectQueryInterface A new SelectQuery object with no fields or expressions besides COUNT(*).

Overrides SelectQueryInterface::countQuery


includes/database/select.inc, line 1447


Query builder for SELECT statements.


public function countQuery() {

  // Create our new query object that we will mutate into a count query.
  $count = clone $this;
  $group_by = $count
  $having = $count
  if (!$count->distinct && !isset($having[0])) {

    // When not executing a distinct query, we can zero-out existing fields
    // and expressions that are not used by a GROUP BY or HAVING. Fields
    // listed in a GROUP BY or HAVING clause need to be present in the
    // query.
    $fields =& $count
    foreach (array_keys($fields) as $field) {
      if (empty($group_by[$field])) {
    $expressions =& $count
    foreach (array_keys($expressions) as $field) {
      if (empty($group_by[$field])) {

    // Also remove 'all_fields' statements, which are expanded into tablename.*
    // when the query is executed.
    foreach ($count->tables as $alias => &$table) {

  // If we've just removed all fields from the query, make sure there is at
  // least one so that the query still runs.

  // Ordering a count query is a waste of cycles, and breaks on some
  // databases anyway.
  $orders =& $count
  $orders = array();
  if ($count->distinct && !empty($group_by)) {

    // If the query is distinct and contains a GROUP BY, we need to remove the
    // distinct because SQL99 does not support counting on distinct multiple fields.
    $count->distinct = FALSE;
  $query = $this->connection
  return $query;