Search code examples
salesforceapex-codesoql

Clarification on governor limits for soql queries


Setup:

Say I have five Contact sObjects that I create and apex. When you insert a contact one at a time, you have x soql queries by way of triggers and stuff it uses.

Questions:

  1. So if you insert each contact one at a time in your code you get 5x soql queries (right?).

  2. Now say you put those 5 guys into an array and insert the array using one insert. How many soql queries are there?

  3. In regards to 2, if It’s 5x, why do we bother? So we can decrease the number of DML's by 4?

Thanks,

The semi-new guy


Solution

  • A given block of code and all of the synchronous apex code that executes because of it is evaluated in a single execution context, which means that it has a single set of governor limits. In the example that you give, suppose that your Contact trigger makes 3 SOQL queries and one DML statement. If you inserted each contact separately, then you would use 5 DML statements (one for each Contact insert) + 1 DML statement for each trigger, and 3 * 5 SOQL statements for each trigger, leading to a total of 15 SOQL statements and 10 DML statements for your code. However, if you inserted them as a list, then all five records would be sent as a list to your trigger (1 DML statement) which would then execute its 3 SOQL queries and 1 DML statement once, for a total of 3 SOQL queries and 2 DML statements.

    The key here is to design your triggers (and most of your other code) so that the number of queries and statements is not dependent on the number of records you are dealing with. Salesforce provides a brief guide for that here: http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_triggers_bulk_idioms.htm