COUNT() and COUNT(fieldName)

To discover the number of rows that a query returns, use the aggregate function COUNT() in a SELECT statement of a SOQL query.

COUNT()

COUNT() returns the number of rows that match the filtering conditions.

For example:

1SELECT COUNT()
2FROM Account
3WHERE Name LIKE 'a%'
1SELECT COUNT()
2FROM Contact, Contact.Account
3WHERE Account.Name = 'MyriadPubs'

For COUNT(), the size field of the QueryResult object returns the number of rows retrieved in the query. The records field returns null.

Note the following when using COUNT():

  • COUNT() must be the only element in the SELECT list.
  • The number of rows returned by COUNT() includes null values that match the filtering conditions of the query.
  • You can use COUNT() with a LIMIT clause.
  • You can't use COUNT() with an ORDER BY clause.

COUNT(fieldName)

COUNT(fieldName) returns the number of rows that match the filtering conditions and have a non-null value for fieldName.

For example:

1SELECT COUNT(Id)
2FROM Account
3WHERE Name LIKE 'a%'

COUNT() and COUNT(Id) in SOQL are similar to COUNT(*) in SQL.

Note

For COUNT(fieldName), the object in the records field returns the number of rows. The size field does not reflect the count. For example:

1SELECT COUNT(Id)
2FROM Account
3WHERE Name LIKE 'a%'

The count is returned in expr0, which is the implied alias for the aggregated field.

You can include multiple COUNT(fieldName) items in a SELECT clause. For example, the following query returns the number of opportunities, and the number of opportunities associated with a campaign.

1SELECT COUNT(Id), COUNT(CampaignId)
2FROM Opportunity

You can use GROUP BY clause with COUNT(fieldName) to analyze your records and return summary reporting information. For example, the following query returns the number of leads for each LeadSource value:

1SELECT LeadSource, COUNT(Name)
2FROM Lead
3GROUP BY LeadSource