Find your content:

Search form

You are here



How do I create a SOQL GROUP BY using custom field?

For example:

SELECT id, name, Cultura__c 
GROUP BY Cultura__c

This returns an error:


Attribution to: Guilherme Gobetti

Possible Suggestion/Solution #1

Salesforce group by example

The gotcha is that in SOQL, you can't use a bare count() in a group by query.

As a work around, you can specify a field to go inside the count like this:

select mycolumn, count(id)
from Opportunity
group by mycolumn

This produces results for me:

mycolumn              Unknown_Field__1
skipper               5
kowalski              3
rico                  1

A more advanced query using group by:

This gets the unique values of insurancecarrier__c and how many there are in the Object called Opportunity. It sorts descending by the 2nd column, and limits to 100 results.

select insurancecarrier__c, count(id)
from Opportunity
group by insurancecarrier__c
order by count(id) desc
limit 100

Attribution to: Eric Leschinski

Possible Suggestion/Solution #2

You should be able to group with a custom field just like a standard one. The main difference is the result from a group by query is that it becomes an AggregateResult sObject.

Salesforce Documentation of SOQL GROUP BY:

Attribution to: Jon Hazan

Possible Suggestion/Solution #3

This is exclusively for SOSL AND SOQL. Defined at this link:

You can use a GROUP BY clause without an aggregated function to query all the distinct values, including null, for an object. The following query returns the distinct set of values stored in the LeadSource field.

SELECT LeadSource
GROUP BY LeadSource

Attribution to: Mohith Shrivastava
This content is remixed from stackoverflow or stackexchange. Please visit

My Block Status

My Block Content