Sub topic 2
Counting Records with COUNT and COUNT_DISTINCT
This chapter assumes you know basic SOQL (SELECT, FROM, WHERE, ORDER BY, LIMIT), understand Salesforce objects and field types, and can read simple Apex. Here you will learn the three ways SOQL counts records and when each one fits.
Why count in the query
You could query every record and call size() on the list. That wastes heap and rows, because every returned row counts against the governor limits. An aggregate query lets the database count the rows and return only the number.
SOQL offers these count forms:
| Form | What it counts |
|---|---|
| `COUNT()` | All rows that match the query. Takes no field. |
| `COUNT(field)` | Rows where `field` is not null. |
| `COUNT_DISTINCT(field)` | Different non-null values of `field`. |
COUNT() with no field
COUNT() returns a single integer for the whole result set. In Apex, put it in a query and the result is an Integer, not a list.
Integer openOpps = [SELECT COUNT() FROM Opportunity WHERE IsClosed = false];
System.debug('Open opportunities: ' + openOpps);COUNT() is the simplest form. It cannot be combined with other selected fields or with an alias. If you need either, use COUNT(Id).
COUNT(field)
COUNT(Id) counts rows too, because Id is never null. With any other field, rows where that field is empty are skipped. This query shows the difference:
AggregateResult ar = [
SELECT COUNT(Id) allLeads, COUNT(Email) leadsWithEmail
FROM Lead
];
System.debug(ar.get('allLeads') + ' leads, ' + ar.get('leadsWithEmail') + ' with an email');The aliases allLeads and leadsWithEmail name the results. A later chapter covers aliases and AggregateResult in detail. For now, note that an aggregate query with a field returns an AggregateResult row, and you read each value with get().
COUNT_DISTINCT
COUNT_DISTINCT(field) counts each value once, no matter how many records share it. Null values are not counted.
SELECT COUNT_DISTINCT(Industry) industryCount
FROM AccountIf 500 accounts spread across 12 industries, this returns 12. COUNT(Industry) would return the number of accounts that have an industry, up to 500.
Counting per group
Counts become more useful when combined with GROUP BY, which returns one row for each distinct value of a field. This query counts leads per lead source:
SELECT LeadSource, COUNT(Id) leadCount
FROM Lead
GROUP BY LeadSourceLeads with no source are grouped together in one row where LeadSource is null. The next chapters cover grouping in full.
Common errors
- Casting the wrong type. In Apex,
ar.get('allLeads')returns anObject. Cast it toIntegerbefore doing arithmetic. - Expecting nulls to count.
COUNT(field)andCOUNT_DISTINCT(field)both ignore null values. - Using
COUNT()withLIMITand expecting a capped count. The count is computed on the matching rows. Check the limits for your context before relying on very large counts.
Exercise
An Account object has 200 records. 150 have an Industry value, spread over 9 different industries. What do COUNT(), COUNT(Industry), and COUNT_DISTINCT(Industry) return?
Show answer
COUNT() returns 200, because it counts every matching row. COUNT(Industry) returns 150, because it skips the 50 rows where Industry is null. COUNT_DISTINCT(Industry) returns 9, the number of different non-null values.
Exercise
Write a SOQL query that returns the number of different LeadSource values among Leads, with the alias sourceCount.
Show answer
SELECT COUNT_DISTINCT(LeadSource) sourceCount FROM Lead