Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

I can't think how to write a query to return all the contacts and all the leads (IDs, Names, and Phones) from CampaignMember.

I've never used much else rather than the standard [SELECT field FROM object WHERE criteria] format so I don't really know where to start.

At the start of the function I have the Id of the campaign, and two empty lists of Contact and Lead, which I'd like to populate. Can anyone help?

share|improve this question

2 Answers 2

up vote 3 down vote accepted

You should be able to do something like:

List<Contact> contacts = [
    SELECT 
        Id, Name, Phone 
    FROM 
        Contact 
    WHERE 
        Id IN (
            SELECT 
                ContactId 
            FROM 
                CampaignMember 
            WHERE 
                Id = :campaignId AND ContactId != null
        )
];

List<Lead> leads = [
     SELECT 
         Id, Name, Phone 
     FROM 
         Contact 
     WHERE 
         Id IN (
             SELECT 
                 LeadId 
             FROM 
                 CampaignMember 
             WHERE 
                 Id = :campaignId 
                 AND LeadId != null
         )
 ];
share|improve this answer
    
It worked :) thanks –  Adam Jun 17 at 13:25
    
Actually the Id field in the nested SELECT should be CampaignId, but still. –  Adam Jun 18 at 12:50

The following SOQL will give you the ContactId and LeadId for Campaigns with an particular id:

SELECT ContactId,LeadId FROM CampaignMember WHERE CampaignId='XXX'

If you need to get details of the contacts and leads you can just use relationships like the following:

SELECT ContactId, Contact.FirstName, Contact.LastName, Contact.Phone, LeadId, Lead.FirstName, Lead.LastName, Lead.Phone FROM CampaignMember WHERE CampaignId='XXX'

To get the lead and contacts separately you could do the following:

SELECT ContactId, Contact.FirstName, Contact.LastName, Contact.Phone FROM CampaignMember WHERE CampaignId='XXX' AND ContactId<>''

and

SELECT LeadId, Lead.FirstName, Lead.LastName, Lead.Phone FROM CampaignMember WHERE CampaignId='XXX' AND LeadId<>''
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.