+ Start a Discussion

Delete Orphaned records



I am stuck in a issue that looks simple. I have a object which has related record in a child object. If the parent object record is deleted, then the child object record should be deleted. I have implemented this using triggers.


But the issue is how to delete already orphaned records. The requirement is to delete orphaned records that does not have any matching parent records.






If the child object is defined as a Master-Detail, then the child records are automatically deleted when the parent is deleted (ie cascade delete).


If the child object is defined as a Lookup, then you could deploy a trigger on delete to query and delete the child objects.


Here is some psuedo-code to get you started:


trigger onParentObjectDelete on CustomObject__c (before delete){ List<Id> idsToQuery = new List<Id>{}; for(CustomObject__c a: Trigger.new){ idsToQuery.add(a.id); } //query all child records where parent ids were deleted ChildObject__c[] objsToDelete = [select id from ChildObject__c where ParentId__c IN :idsToQuery]; delete objsToDelete; //perform delete statement }






Thanks Albert.


I have already implemented the trigger so that it would delete the recrods from the child too. My issue is dealing with already orphaned records before the tirgger was implemented. How would I find the records that have been deleted from the parent object but without deleting matching child records and run the data loader to delete the the orphans?



I would think the ParentId__c lookup field is null since the parent record has been deleted.

Albert has the right idea
ChildObject__c[] objsToDelete = [select id from ChildObject__c where ParentId__c = null];

When the lookup object of a field is deleted, all object references pointing to it become null after it has been deleted.

If you make your trigger run on after delete, you'll just need to run the query where ParentId__c = null

Message Edited by Whyser on 03-02-2009 03:39 PM

And if you undelete the ParentId__c and if you want to restore the deleted childs as well automatically ? 


I'm having this problem. Please have a look here : http://community.salesforce.com/sforce/board/message?board.id=apex&thread.id=13242




Thanks for the example.

One point: I had to replace the Trigger.new by Trigger.old to get this piece of code working.