SOQL aggregate query limit [Updated for Summer18]

I think that the issue here is that an aggregate query is considered to have accessed every record included in the aggregation. Thus the 50000 row limit isn't the number of records returned by the query, its the number of records 'touched'. As you have a clause of 'LIMIT 50000', you are asking for a maximum of 50000 aggregates to be returned by the query and if any of these "touches" more than one record, you will exceed the limit.

The only exception to this is if your class is annotated @readonly, in which case there are no record limits on queries (although the others still apply, (e.g. heap space). However, this can only be used in scheduled classes or webservices, so may not be useful in your situation.

If you can't use @readonly, you'll need to set the value of the LIMIT clause to one which is low enough that all of the records considered in the aggregations is less than 50000. If you have cities that have more than 50000, then there won't be a low enough limit.

If the relationship between building and city is master detail, you could use a roll up summary field to calculate the averages, although you are limited to 10 of these fields per record.


Limit Clause will not take effect in the Aggregate Functions, you have to use the Where Clause to limit the data size in the query.

See the Note in the SOQL documentation:

Queries that include aggregate functions are subject to the same governor limits as other SOQL queries for the total number of records returned. This limit includes any records included in the aggregation, not just the number of rows returned by the query. If you encounter this limit, you should add a condition to the WHERE clause to reduce the amount of records processed by the query.


SOQL count query now counts as 1. So you can count all the things.

https://releasenotes.docs.salesforce.com/en-us/summer18/release-notes/rn_apex_soql_count_limits.htm