+ Start a Discussion
jucuzoglujucuzoglu 

Trouble getting distinct values in SOQL query

I want to grab the Contact Records associated with CampaignMember records that meet a particular criteria.

 

If APEX/SOQL supported DISTINCT I would run the following query:

 

Select Id,Name from Contact Where ID IN
(Select DISTINCT ContactID from CampaignMember where SomeCondition = true)

 I would not be too concerned with needing Distinct except the secondary query is too large without it.

 

I tried the statement above and using the Group By statement which (when run by itself) returns unique results however the IN clause does not seem to support grouped results and throws an error.

 

Perhaps there is a better way for me to go about this? I anticipate that the number of CampaignMember records that meet the criteria is aproximatly 75000 but they only repersent around 15,000 unique Contact records. 

Devendra@SFDCDevendra@SFDC

Hi,

 

Apex does not support DISTINCT in soql.

 

Here is an idea for having distinct in apex,

https://success.salesforce.com/ideaView?id=08730000000Brr2

kiranmutturukiranmutturu
List<CampaignMember > lstCM = new List<CampaignMember>();

Set<String> setContactID = new Set<String>();

lstCM = [Select DISTINCT ContactID from CampaignMember where SomeCondition = true];


for (Integer i = 0; i< lstCM.size(); i++)
{
setContactID .add(lstCM[i].ContactID); // contains distict contacts
} then use

Select Id,Name from Contact Where ID IN :setContactID