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
aamDevaamDev 

Retrieve Contact Id Where Event and Task Subqueries Not Null

I need to create a list of distinct Contact Ids from Contacts that have an Event or Task tied to them within a time period. I know one way to create a distinct list is to grab the WhoIds from Event and Task and add them to a Set<Id> like:

 

 

Set<Id> contactSet = new Set<Id>();
for (Event e : [SELECT WhoId FROM Event WHERE ActivityDate >=: startDate AND ActivityDate <=: endDate]) {
	contactSet.add(e.WhoId);
}
for (Task t : [SELECT WhoId FROM Task WHERE ActivityDate >=: startDate AND ActivityDate <=: endDate]) {
	contactSet.add(t.WhoId);
}

 

 

The problem with this is that either loop could retrieve 'Too many query rows'. I could group by WhoId in either one, making an AggregateResult, but with a large enough set of Contacts, I'd run across the queryMore() limitation with AggregateResult.

 

So, I figured I'd try to run a query on Contact with Event and Task subqueries like:

 

 

SELECT Id, (SELECT Id FROM Tasks WHERE ActivityDate >=: startDate AND ActivityDate <=: endDate), (SELECT Id FROM Events WHERE ActivityDate >=: startDate AND ActivityDate <=: endDate) FROM Contact

 

 

How would I populate my Set<Id> contactSet with the Contact Ids where the Task or Event subquery does not equal null?

 

Thanks, I appreciate the help.

 

A

Best Answer chosen by Admin (Salesforce Developers) 
aamDevaamDev

I figured it out. For anyone interested:

 

 

Set<Id> contactSet = new Set<Id>();
SObject[] c = Database.query('SELECT Id, (SELECT Id FROM Events WHERE ActivityDate >=: startDate AND ActivityDate <=: endDate AND Who.Type = \'Contact\'), (SELECT Id FROM Tasks WHERE ActivityDate >=: startDate AND ActivityDate <=: endDate AND Who.Type = \'Contact\') FROM Contact WHERE Active__c = True AND Account.RecordTypeId = \'01230000000Q9p4AAC\' AND Account.Parent.Broker_Number__c =:dist174');
for (SObject cReps : c) {
	SObject[] cEvents = cReps.getSObjects('Events');
	SObject[] cTasks = cReps.getSObjects('Tasks');
	if(cEvents != null || cTasks != null) {
		contactSet.add(cReps.Id);
	}
}