Inner Query in Query Locator Bad Practice

    sfdcsharepoint.com

    Recently came across one code which had inner query in QueryLocator. For example some one has put that in Start method of Batch apex.

    n

    To give exact example of Query in Start Method of Batch,

    global Database.QueryLocator start(Database.BatchableContext BC) {n    query = 'Select Id, (Select Id From Attachments) From Account'n    return Database.getQueryLocator(query);n}

    I think this is not the right way of doing query.

    n

    To get into the reason why, i think this Link will help you.

    In a SOQL query with parent-child relationship sub-queries, each parent-child relationship counts as an additional query.

    n

    The row counts from these relationship queries contribute to the row counts of the overall code execution.

    nn

    In addition to static SOQL statements, calls to the following methods count against the number of SOQL statements issued in a request

      n

    1. Database.countQuery
    2. n

    3. Database.getQueryLocator
    4. n

    5. Database.query
    6. n

    n

    For example your org contain  only 2 Account and each have 10 Contacts.

    n

    If you execute this with sub Query like below

    n

    Select Id, Name, (Select Id, Name from Contacts) From Account

    n

    Then the total number of Query rows will be 22 (2+10+10).

    n

    From above analogy we can understand like this, If your org contain 40M accounts and each have 1 contact. Then in this scenario you can use sub query up to 25M only.

    n

    Like this Select Id, Name, (Select Id, Name from Contacts) From Account limit 25M

    n

    Leave a Reply

    Your email address will not be published. Required fields are marked *