How to Select DISTINCT values in SOQL

Manisha Nundloll-Rice
1 min readMay 6, 2021

Have you ever had the need to retrieve distinct values from your database table in Salesforce and been stuck as SOQL does not provide the ability to use DISTINCT in its queries like other query languages?

E.g. If I have a table with non-unique values

Table with non-unique names

Use the following query to mimic the use of the distinct keyword like in other query languages. This is great for running quick queries in query Editor, workbench, etc.

SELECT count(Id), Name FROM Participant__c GROUP BY Name

To access the unique names in Apex, you could do something like this or simply use sets.

AggregateResult[] results = [SELECT count(Id), Name FROM Participant__c GROUP BY Name];
List<String> uniqueNames = new List<String>();
for (AggregateResult result : results) {
uniqueNames.add((String)result.get(‘Name’));
}
system.debug(uniqueNames);

Using Sets

Set<String> uniqueNames = new Set<String>();
for (Participant__c p : [SELECT Name FROM Participant__c]) {
uniqueNames.add(p.Name);
}

--

--

Manisha Nundloll-Rice

Salesforce Developer/Lead with over 10 years of Salesforce Experience. Experience in Apex, VisualForce, Lightning Web Components.