Aggregate SOQL – How Many Fields Can Be Grouped?

As stated in the title, is there any maximum on the number of fields that can be passed into a GROUP BY clause? I can’t find any documentation on it. For example, if I had the following query:

SELECT count(Id) records
FROM My_Object__c
GROUP BY Field1__c, Field2__c, ..., FieldN__c

what would be the max N?

Answer

The maximum is 32 groupings. If you exceed this, you receive the following error:

System.QueryException: Group By must contain 32 fields or less

This used to be in the documentation, but I can’t seem to find it now.

Proof

Set<String> fields = lead.sobjecttype.getdescribe().fields.getmap().keyset();
Database.query('select id from lead group by '+string.join(new list<string>(fields), ','));

Attribution
Source : Link , Question Author : Adrian Larson , Answer Author : Community

Leave a Comment