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
Snehil KarnSnehil Karn 

soql in clause with trigger.new

Hello everyone,

I recently went through a trigger which had a SOQL query like this:
 
trigger SoqlTriggerBulk on Account(after update) {  
    // Perform SOQL query once.    
    // Get the accounts and their related opportunities.
    List<Account> acctsWithOpps = 
        [SELECT Id,(SELECT Id,Name,CloseDate FROM Opportunities) 
         FROM Account WHERE Id IN :Trigger.New];
  
    // Iterate over the returned accounts    
    for(Account a : acctsWithOpps) { 
        Opportunity[] relatedOpps = a.Opportunities;  
        // Do some other processing
    }
}

Here I see that in the WHERE clause of the SOQL, user directly passed Trigger.new with IN clause. Is this the correct method? if yes, Is this method encouraged? How can you pass a list of object in the IN clause?

Till now I would have used either a list of Ids to pass in the IN clause or Trigger.newMap.Keyset().
This is also mentioned in on of the trails: https://trailhead.salesforce.com/trails/force_com_dev_beginner/modules/apex_triggers/units/apex_triggers_bulk
Amit Chaudhary 8Amit Chaudhary 8
 Trigger.new is a list of sObjects and can be iterated over in a for loop, or used as a bind variable in the IN clause of a SOQL query.
Trigger simpleTrigger on Account (after insert) {
    for (Account a : Trigger.new) {
        // Iterate over each sObject
    }

    // This single query finds every contact that is associated with any of the
    // triggering accounts. Note that although Trigger.new is a collection of  
    // records, when used as a bind variable in a SOQL query, Apex automatically
    // transforms the list of records into a list of corresponding Ids.
    Contact[] cons = [SELECT LastName FROM Contact
                      WHERE AccountId IN :Trigger.new];
}

https://trailhead.salesforce.com/en/modules/apex_triggers/units/apex_triggers_bulk

 
RKSalesforceRKSalesforce
Hi Snehill,

I don't need to write query in your trigger you can get those Account records in Trigger,New. Use below code it should work fine.
 
trigger SoqlTriggerBulk on Account(after update) {  
      
    // Iterate over the returned accounts    
    for(Account a : Trigger,New) { 
        Opportunity[] relatedOpps = a.Opportunities;  
        // Do some other processing
    }
}

Please let me know if helped.

Regards,
Ramakant