function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
prashanth murukondaprashanth murukonda 

What is GROUP BY in SOQL?

What is GROUP BY in SOQL.When to use it in SOQL?
NagendraNagendra (Salesforce Developers) 
Hi Prashanth,

You can use the GROUP BY option in an SOQL query to avoid iterating through individual query results. That is, you specify a group of records instead of processing many individual records.

With API version 18.0 and later, you can use GROUP BY with aggregate functions, such as SUM() or MAX(), to summarize the data and enable you to roll up query results rather than having to process the individual records in your code.

The syntax is:
[GROUP BY fieldGroupByList]
fieldGroupByList specifies a list of one or more fields, separated by commas, that you want to group by. If the list of fields in a SELECT clause includes an aggregate function, you must include all non-aggregated fields in the GROUP BY clause.

For example, to determine how many leads are associated with each LeadSource value without using GROUP BY, you could run the following query:
SELECT LeadSource FROM Lead
You would then write some code to iterate through the query results and increment counters for each LeadSource value. You can use GROUP BY to get the same results without the need to write any extra code. For example:
SELECT LeadSource, COUNT(Name)
FROM Lead
GROUP BY LeadSource
Please mark this as solved if the information helps so that it gets removed from the unanswered queue which results in helping others who are encountering a similar issue.

Regards,
Nagendra.