Rows counted with size() instead of SELECT COUNT()

ID

apex.performance.soql_count_instead_size

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Performance

Language

Apex

Description

Reports a SOQL query whose result is only counted, by calling size() directly on the query.

Rationale

The query returns every matching row into the heap before size() looks at how many there are: on a large object that is the 6 MB synchronous heap limit and a QueryException: Too many query rows: 50001 for a number the database could have returned on its own. SELECT COUNT() is answered by the index and costs one row of heap regardless of how many records match.

The following code illustrates the pattern detected by this rule:

public class RowCounting {

    public Integer countAccounts(String name) {
        // FLAGGED: Rows counted with size() instead of SELECT COUNT()
        Integer total = [SELECT Id FROM Account WHERE Name = :name].size();
        return total;
    }

    public Integer countAccountsAggregate(String name) {
        Integer total = [SELECT COUNT() FROM Account WHERE Name = :name];
        return total;
    }

    public Integer countLoaded(String name) {
        List<Account> accts = [SELECT Id, Name FROM Account WHERE Name = :name];
        return accts.size();
    }
}

Remediation

Use the aggregate form - Integer total = [SELECT COUNT() FROM Account WHERE …​]; - which returns the count directly. Where the records themselves are needed as well, keep the row query and count the list you already hold rather than querying twice.

Configuration

This detector does not need any configuration.

© 2026 Xygeni. All rights reserved