I have an object(Huishouden__c) with a related list. I loop trough the object records with a for loop on the related record. When I debug the object in the first loop I get an Id but it does not enter the second loop?

[SELECT id FROM Huishouden__c WHERE id IN : uniqueHuish]

This returns an Id, I doent see any errors in my debug


 List<Huishouden__c> deleteHuish = new List<Huishouden__c>(); 
    for(Huishouden__c h: [SELECT id FROM Huishouden__c 
                          WHERE id IN : uniqueHuish]) {
                              system.debug('SELECT id FROM Huishouden__c'+ [SELECT id FROM Huishouden__c WHERE id IN : uniqueHuish]);
                              for(Relatie__c rc : h.Relatie_Contacten__r) { 
                                  if(h.Relatie_Contacten__r.size()<=1) {
    delete deleteHuish;
    system.debug('deleteHuish '+deleteHuish);
  • Don't you need to query for child records in the first SOQL for loop? Like - SELECT id,(Select id from Relatie_Contacten__r) FROM Huishouden__c WHERE id IN : uniqueHuish
    – Suneel
    Commented May 28, 2018 at 5:14

1 Answer 1


According to your code, you need to execute a SOQL to fetch the child records which you are not doing currently. Thats why it is not entering inner for loop.

Since, you are checking the count and trying to delete records, you can follow this most optimized approach.

Prepare an Aggregate query like this and execute the delete operation. Be sure to verify the related parent field (e.g. Huishouden__c ) from child object Relatie__c based on which you will be grouping the records.

List<Huishouden__c> deleteHuish = new List<Huishouden__c>(); 
List<AggregateResult> results = [SELECT Huishouden__c, COUNT(Id) idCount
                                    FROM Relatie__c
                                    WHERE Huishouden__c IN:uniqueHuish
                                    GROUP BY Huishouden__c
                                    HAVING COUNT(Id) <2];

for(AggregateResult result: results)
    Huishouden__c obj = new Huishouden__c(Id = (String) result.get('Huishouden__c'));
delete deleteHuish;
  • Thank you. I tried the count part before in subquery which didnt work, but figured out now what was wrong with my annotation.
    – Thomas
    Commented May 28, 2018 at 5:51
  • for this kind of use case prefer to use Aggregate query Commented May 28, 2018 at 5:52

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .