Wednesday 29 August 2018

Soql Queries and Sub Queries


In the below query there are total 3 subqueries + 1 parent query. So, there are 4 queries. But, Salesforce doesn't count subqueries against governor limit of 100 SOQLs. It counts only root query which means only 1 SOQL query would be consumed.


List<Account> dd = [
    SELECT
        id,
        (SELECT Name FROM Contacts),  // <- first subquery
        (SELECT AccountID FROM Cases) // <- second subquery
    FROM
        Account
    WHERE
        id
    IN (SELECT AccountID FROM Case)   // <- not counted
];


Subqueries are counted separately as AggregateQueries. You can check those with Limits.getAggregateQueries() and Limits.getLimitAggregateQueries(). You cannot have more than 300 aggregations in a single transaction.

For example: Org contain  only 2 Account and each have 10 Contacts.

 If you execute this with sub Query like below

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

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

 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.

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