Sub topic 2
Counting records with COUNT and COUNT_DISTINCT
This chapter assumes you can write basic SOQL (SELECT, FROM, WHERE, ORDER BY, LIMIT), know Salesforce objects and field types, and can read simple Apex with variables, loops, and casting. It covers the three counting forms SOQL offers and how they treat null values and query results. Later chapters add GROUP BY.
Why count in the query
Counting is the most common aggregate task. You might want the number of open cases or the number of distinct industries across your accounts. You could query the records and call size() on the list, but that retrieves every row. It uses heap memory and counts against the limit on rows retrieved. An aggregate query makes the database do the counting and sends back one number.
SOQL has three counting forms:
COUNT()with empty parentheses.COUNT(fieldName).COUNT_DISTINCT(fieldName).
They look alike, but they return different result types and treat nulls differently.
COUNT() with no argument
COUNT() returns the number of rows that match the query. In Apex, a query that selects only COUNT() evaluates directly to an Integer.
Integer openCases = [SELECT COUNT() FROM Case WHERE IsClosed = false];
System.debug('Open cases: ' + openCases);Three rules apply to this form:
- It must be the only item in the
SELECTlist. You cannot writeSELECT COUNT(), Name FROM Account. - It cannot take an alias, because the result is not an
AggregateResultrow. - It is the simplest choice when you need a single total and nothing else.
Because the result is an Integer, you do not cast anything. This is also the only counting form that returns a plain number in Apex.
COUNT(fieldName)
COUNT(fieldName) counts the rows where that field is not null. The result comes back as an AggregateResult, in the same way as SUM or AVG.
SELECT COUNT(Id) leadCount
FROM LeadId is never null, so COUNT(Id) counts every matching row. It is the usual way to ask "how many rows?" when you also need other aggregates or a GROUP BY in the same query. Any other field counts only the rows where it has a value:
SELECT COUNT(Id) allLeads, COUNT(Email) leadsWithEmail
FROM LeadIf 1,000 leads exist and 700 have an email address, this returns 1000 and 700 in one row. The difference between the two numbers is the count of leads with no email.
The word after the expression (allLeads, leadsWithEmail) is an alias. Aliases are covered in their own chapter. For now, remember that they are written without AS and that they let you read the value by name in Apex.
COUNT_DISTINCT(fieldName)
COUNT_DISTINCT(fieldName) returns how many different non-null values a field holds across the matching rows.
SELECT COUNT_DISTINCT(Industry) industryCount
FROM AccountIf your accounts use 12 different Industry values, the result is 12. Accounts with a blank Industry are ignored. Blank is not counted as a 13th value.
The three forms compared
| Form | Counts | Nulls | Apex result | Alias allowed |
|---|---|---|---|---|
| `COUNT()` | Matching rows | Rows are counted regardless | `Integer` | No |
| `COUNT(Id)` | Matching rows | `Id` is never null | `AggregateResult` | Yes |
| `COUNT(Industry)` | Rows with a value in `Industry` | Skipped | `AggregateResult` | Yes |
| `COUNT_DISTINCT(Industry)` | Different values in `Industry` | Skipped | `AggregateResult` | Yes |
The diagram shows how to choose between them.
Reading the results in Apex
A query with COUNT(Id) or COUNT_DISTINCT(...) returns AggregateResult rows, even when there is only one row. You can assign a single-row result directly to an AggregateResult variable and call get with the alias. The returned value is an Object, so cast it to Integer.
AggregateResult ar = [
SELECT COUNT(Id) totalAccounts,
COUNT(Industry) withIndustry,
COUNT_DISTINCT(Industry) distinctIndustries
FROM Account
];
Integer totalAccounts = (Integer) ar.get('totalAccounts');
Integer withIndustry = (Integer) ar.get('withIndustry');
Integer distinctIndustries = (Integer) ar.get('distinctIndustries');
System.debug(totalAccounts + ' accounts, ' + withIndustry
+ ' with an industry, ' + distinctIndustries + ' distinct industries');An ungrouped aggregate query always returns exactly one row, even if no records match the WHERE clause. In that case the counts are 0, so the single-row assignment is safe.
If you leave off the alias, Salesforce names the column expr0, expr1, and so on, in order of position. Reading ar.get('expr0') works, but it breaks silently if someone reorders the select list. Use explicit aliases.
Counting with GROUP BY
Combined with GROUP BY, COUNT(Id) gives one count for each distinct value of the grouped field.
SELECT LeadSource, COUNT(Id) leadCount
FROM Lead
GROUP BY LeadSourceThe result has one row per distinct LeadSource value. Leads with no source form their own row, where LeadSource is null. So grouping does not skip nulls the way COUNT_DISTINCT does. The next chapters cover grouping in detail.
This difference matters when you compare results. Suppose your leads use 8 different sources, and some leads have no source. The grouped query returns 9 rows, but COUNT_DISTINCT(LeadSource) returns 8.
Filtering before you count
A WHERE clause filters rows before any counting happens. All three forms respect it.
SELECT COUNT_DISTINCT(Industry) industryCount
FROM Account
WHERE BillingCountry = 'United States'This counts the different industries among United States accounts only. A later chapter covers how WHERE differs from HAVING, which filters groups after counting.
Common mistakes
- Mixing
COUNT()with other fields.SELECT COUNT(), Industry FROM Accountis invalid. UseCOUNT(Id)and aGROUP BYinstead. - Casting the wrong way.
COUNT(Id)returns anAggregateResult, not anInteger. AssigningInteger n = [SELECT COUNT(Id) FROM Lead];fails to compile. Either useCOUNT()for the plainInteger, or read the value withgetand cast it. - Expecting
COUNT(field)to count all rows. It skips nulls. If a total is what you want, countId. - Expecting
COUNT_DISTINCTto include null as a value. It does not. Compare the result with the number of rows from aGROUP BYif blanks matter to you. - Retrieving rows just to count them.
[SELECT Id FROM Lead].size()pulls every row into memory and counts toward the row limit. ACOUNT()query does not. - Relying on
expr0. Without an alias, the field name depends on position. Add an alias.
Putting it together
This example reports how complete the Industry field is on accounts. It uses all three aggregate counting expressions in one query.
AggregateResult ar = [
SELECT COUNT(Id) total,
COUNT(Industry) filled,
COUNT_DISTINCT(Industry) kinds
FROM Account
WHERE IsDeleted = false
];
Integer total = (Integer) ar.get('total');
Integer filled = (Integer) ar.get('filled');
Integer kinds = (Integer) ar.get('kinds');
Decimal pct = total == 0 ? 0 : (Decimal.valueOf(filled) / total * 100).setScale(1);
System.debug(pct + '% of accounts have an Industry, spread over ' + kinds + ' values');The total == 0 check avoids a divide-by-zero error on an org with no accounts. Here IsDeleted = false is already the default for normal queries, so the filter changes nothing. It is shown only to illustrate a WHERE clause on an aggregate query.
Exercise
A Lead object has 500 records. 450 have a LeadSource value, spread over 6 different values. The other 50 have no LeadSource. What does each of these return? (a) SELECT COUNT() FROM Lead (b) SELECT COUNT(LeadSource) c FROM Lead (c) SELECT COUNT_DISTINCT(LeadSource) d FROM Lead (d) the number of rows returned by SELECT LeadSource, COUNT(Id) n FROM Lead GROUP BY LeadSource
Show answer
(a) 500, as an Integer in Apex. (b) 450, because null values are skipped. (c) 6, because only distinct non-null values are counted. (d) 7 rows: one for each of the 6 values plus one row where LeadSource is null.
Exercise
This Apex line fails to compile: Integer n = [SELECT COUNT(Id) FROM Contact]; Give two ways to fix it.
Show answer
Change the query to SELECT COUNT() FROM Contact, which evaluates directly to an Integer. Or keep COUNT(Id) with an alias, assign the query to an AggregateResult variable, and read the value with (Integer) ar.get('alias').