Is it possible to do a "SOQL for loops" for a collection? I want to know the number of Assets for each AccountID.

At first time I created a set that contains the AccountID and I used the SOQL for Loops to query Asset Object.

Set<Id> setIDAccount = new Set<Id>();
for(List<Asset> listAsset : [SELECT id, AccountId FROM Asset]){
    for(Asset a : listAsset)

At this point I want do a query for each ID present in setIDAccount and get the number of Asset for this AccountID. The simplest way is to do a for:

for(Id i : setIDAccount){
  System.debug([SELECT COUNT() FROM Asset WHERE AccountID =: i]);

The code is ok but I would write a better version. Is it possible not to use the FOR LOOP to iterate on set and do a query in it? How can I do it in a bulk way?

Thanks :)


As Account and Assets are related, you can use a sub query to querty/count assets using its Relationship Name.

Using a Workbench, identify the Relation Name for Asset object and then perform a query.

In your code, you have written a SOQL inside a for loop. This will give SOQL Exception error if you have more than 100 account records.

enter image description here

List<Account> accountList = [Select id, (Select Id from Assets) from Account]; // Add Where Condition fro Account

for(Account objAccount : accountList){
   System.debug('Count Assets ###'+objAccount.Assets.size());
  • Thanks a lot! It's a perfect solution but I have a curiosity: Isn't possible do a "SOQL Loops" for a collection? – vt89 Oct 13 '16 at 11:01
  • I'm glad, it worked for you! – Devendra Oct 13 '16 at 17:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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