Saturday, June 1, 2019

How to Get List of All Child Records for Given Parent Records in .csv File using Apex

If we have lot of child object for a parent object, then it becomes very difficult to find out list of all related records for a given parent. For example, Account and Contact is reference by many standard and custom objects.

Consider a scenario in which Account is parent for more than 50 objects. In this case if we have to check if account record is being reference in any of these child objects, then how we are going to do that.  Its very difficult to add all related list on account page layout or to write SOQL queries to get this information.

If we use nested queries as mentioned below, then we have limit to use only 20 nested queries.

select id, (Select id from Cases),(Select id from Contacts) from Account where Id='0010000xxxxxxx'

In order to overcome these issues, I have written a script which you can run in developer console and you will receive email with .csv file containing all child records for a given parent record.

In below mentioned script, specify the object API name and 15 or 18 digit record id.

After running this script, you will receive .csv file in email as shown below:


If you are getting below mentioned error, while running the script, the make note of below points:


  • This exception can not be handled by try and catch
  • SOQL is not performing well may be because the large volume of data or due to indexing issues on table.
  • Instead of running this script developer console, use batch apex to run this logic. You can create a custom object and first run a script to store all child objects details like relationship name, child object name. Then you can execute the logic in batch class to first fetch all these records from custom object and then fire nested queries by using relation names and store output in variable. Make sure your batch size is not greater than 20 as we have limit of 20 nested queries in SOQL. In finish method write send email code to get .csv file. If you are still getting this error, then keep on reducing the batch size.
Hope this will help!!

Looking forward for your comments and suggestions.



3 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. I definitely enjoying every little bit of it. It is a great website and nice share. I want to thank you. Good job! You guys do a great blog, and have some great contents. Keep up the good work. Baby Formula

    ReplyDelete
  3. Hello I am so delighted I located your blog, I really located you by mistake, while I was watching on google for something else, Anyways I am here now and could just like to say thank for a tremendous post and a all round entertaining website. Please do keep up the great work. Baby Wipe Warmer

    ReplyDelete