Formula field cannot be grouped in SOQL GROUP BY in SOQL

Description

Yes, it’s Salesforce restriction, as Formula fields are not indexed and groupable, query will become very slow; so Salesforce does not allow group in SOQL.

SELECT count(Id) FROM Lead GROUP by Formula_Field__c

Workaround

  • Create a custom field with same return type as Formula field has.
  • Populate the value in this custom field using flow. This flow will be triggered on record creation/updation with Fast Field Updates.
  • This flow populates the field using same formula in flow.
  • Use this custom field in SOQL.