Let's say I have a following piece of code:

Set<Id> accountIds = new Set<Id>();

for(Contact c : [SELECT Name FROM Contact WHERE AccountId IN :accountIds]){

The accountIds set is obviously empty in the example above, but will my Apex code consume 1 SOQL query?


Yes, even though the Set<Id> accountIds is empty, 1 SOQL query will be executed and will be counted against the 100 SOQL queries limit.

On a similar note, the code below won't be counted as 1 DML statement:

List<Account> accounts = new List<Account>();
update accounts;
  • 3
    Thats why, before firing SOQL query better to check the size of Collection, where as in case of DML, no need to check isEmpty() – Santanu Boral Feb 27 '17 at 18:16
  • 5
    Not too surprising as the where clause could be e.g. NOT IN :accountIds. – Keith C Feb 27 '17 at 18:56

To check the SOQL consumption if an empty collection is passed in WHERE clause, I ran below code, also making a DML in the last line (to check both SOQL and DML)

Set<Id> accountIds = new Set<Id>();
// passing empty collection of ids (accountIds) to feed the below SOQL
Account[] accnts = [SELECT id FROM Account WHERE Id IN: accountIds];
DELETE accnts;

and got this result

Number of SOQL queries: 1 out of 100
Number of query rows: 0 out of 50000
Number of SOSL queries: 0 out of 20
Number of DML statements: 0 out of 150
Number of DML rows: 0 out of 10000

So, working with empty collection in such scenario, the results suggest that

  1. One SOQL will be consumed and count against SOQL limits, hence an if(collection.size()) check should be placed to check the size of the collection before feeding it to the SOQL to avoid counting against SOQL limits.
  2. No DML will be counted, which means, if(collection.size()) check would be an unnecessary before the DML statement.
  • This answer doesn't really address the question. – Adrian Larson Feb 28 '17 at 5:41
  • Yeah @adrian I know, I'm on mobile and will update the answer to include the soql consumption and result asap. Thanks btw. – Mahmood Feb 28 '17 at 6:58
  • @AdrianLarson: done. – Mahmood Feb 28 '17 at 14:57
  • Saw it already and voted to even things out a bit. FYI I didn't place either down-vote, but this answer doesn't really add anything not already there in the other answer. – Adrian Larson Feb 28 '17 at 14:59
  • Thanks for that. You just made it to my list-of-liked-persons, top 1%. :D As for the answer, I thought about removing but then I thought why not present some solution to the problems (efficiency wise) surrounding this question. Results at the end should give the reader something to look-out for and avoid at the same time to make things efficient and stay safe with the SFDC limits. – Mahmood Feb 28 '17 at 15:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.