[SalesForce] Return type of count() versus count(fieldName)

The following code works

Integer i = [select count() from Account];

But the code below results in and error: "Illegal assignment from LIST to Integer LINE: 1 COLUMN: 1"

Integer i = [select count(Id) from Account];

Why is this?

Best Answer

COUNT() is an older SOQL function that was available prior to other aggregate functions. It returns an integer. If you use COUNT(fieldName) the result of the query will be a List instead.

COUNT() is equivalent to COUNT(*) in SQL. It return the total row count. COUNT(fieldName) only counts the number of non-null records. If you want to use COUNT(fieldName), the following code should work:

List<AggregateResult> result  = [select count(Id) total from Account];

For more about the difference between COUNT() and COUNT(fieldName) take a look at the documentation.

Related Topic