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 

Retrieving Values from SOQL Subqueries

I'm trying to slim down the number of SOQL queries I run in a trigger.

 

I currently have these two loops for retrieving Tasks and Events for a Contact:

 

 

for (Event e : [SELECT Id FROM Event WHERE WhoId =: fromId]) {
				
	Event fe = new Event(Id = e.Id, WhoId = toId);
	updateEvent.add(fe);
				
}
			
for (Task t : [SELECT Id FROM Task WHERE WhoId =: fromId]) {
				
	Task te = new Task(Id = t.Id, WhoId = toId);
	updateTask.add(te);
				
}

 

 

They work just fine. However, as mentioned, I would like to reduce my SOQL #. I'd like to be able to run these queries using something like this:

 

 

for (Contact c : [SELECT (SELECT Id FROM Events), (SELECT Id FROM Tasks) FROM Contact WHERE Id =: fromId]) {
				
	Event fe = new Event(Id = c.Events.Id, WhoId = toId);
	updateEvent.add(fe);
				
			
	Task te = new Task(Id = c.Tasks.Id, WhoId = toId);
	updateTask.add(te);
				
}

 

 

Is this possible, and if so, how do I reference the Id fields for both Events and Tasks? I think I've done this somewhere else, I just can't find the example.

 

Thanks in advance,

 

Adriel

Best Answer chosen by Admin (Salesforce Developers) 
aamDevaamDev

Thanks Eric,

 

I found that it was much easier for me to create a VF page and custom controller. The VF page allows me to use up to 100 SOQL queries.

 

Thanks again!

All Answers

crop1645crop1645

Try:

 

 

for (Contact c : [SELECT Id, (SELECT Id FROM Events), (SELECT Id FROM Tasks) FROM Contact WHERE Id =: fromId]) {

   for (Event e: c.events) {
      updateEvent.add(new Event(id = e.id, whoId = toId));

   for (Task t: c:tasks)
      updateTask.add(new Task(id = t.id, whoId = toId));
   }

 

 

aamDevaamDev

Thanks Eric,

 

I found that it was much easier for me to create a VF page and custom controller. The VF page allows me to use up to 100 SOQL queries.

 

Thanks again!

This was selected as the best answer