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:
<!-- otherprops: soql -->SELECT COUNT()
FROM Account
WHERE Name LIKE 'a%'
<!-- otherprops: soql -->
SELECT COUNT()
FROM Contact, Contact.Account
WHERE 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 theSELECTlist.- The number of rows returned by
COUNT()includes null values that match the filtering conditions of the query. - You can use
COUNT()with aLIMITclause. - You can't use
COUNT()with anORDER BYclause.
COUNT(fieldName)
COUNT(fieldName) returns the number of rows that match the filtering conditions and have a non-null value for fieldName.
For example:
<!-- otherprops: soql -->SELECT COUNT(Id)
FROM Account
WHERE Name LIKE 'a%'
note: COUNT() and COUNT(Id) in SOQL are similar to COUNT(*) in SQL.
For COUNT(fieldName), the object in the records field returns the number of rows. The size field does not reflect the count. For example:
SELECT COUNT(Id)
FROM Account
WHERE 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.
SELECT COUNT(Id), COUNT(CampaignId)
FROM 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:
SELECT LeadSource, COUNT(Name)
FROM Lead
GROUP BY LeadSource
See Also