Tuesday 6 June 2017

How to use Limits Apex Methods to avoid Hitting Governor Limits

Many of us facing governor limit error in trigger/classes/test classes. Few of the governor limit errors as follow,

1. Too many SOQL queries: 101
2. Too many dml rows 10001
3. too many query rows 50001.

This article is helpful to verify the Governor Limit by checking limit methods to avoid hitting the governor limit.

Here is the snippet,
  1. System.assert((Limits.getDMLRows() * 100 / Limits.getLimitDMLRows()) < 50);
  2. System.assert((Limits.getDMLStatements() * 100 / Limits.getLimitDMLStatements()) < 50);
  3. System.assert((Limits.getAggregateQueries() * 100 / Limits.getLimitAggregateQueries()) < 50);
  4. System.assert((Limits.getQueries() * 100 / Limits.getLimitQueries()) < 50);
  5. System.assert((Limits.getQueryRows() * 100 / Limits.getLimitQueryRows()) < 50);

Lets take this example,
  1. System.assert((Limits.getQueries() * 100 / Limits.getLimitQueries()) < 50);

In the synchronous transaction, the number of query limit is 100. If it exceeds, then your will get an error like Too many SOQL queries: 101.

  1. Account acc = [SELECT Id FROM Account Limit 1];
  2. System.debug('## Queries Used'+Limits.getQueries());
  3. System.debug('## Total Allowed Queries'+Limits.getLimitQueries());
  4. System.assert((Limits.getQueries() * 100 / Limits.getLimitQueries()) < 50);

Just execute the above snippet in the developer console. We have used one query

## Queries Used --> 1
## Total Allowed Queries --> 100
So as per the assert statement,

(1 * 100 / 100) < 50 --> So the transaction is safe without hitting SOQL limit. Because of query limit is less than 50 out of 100.

References:

Activities: Assign Tasks to a Queue Salesforce Lightning

Salesforce announced to assign Tasks to a Queue beginning from Spring'20 release. How does it work? In Setup, enter Queues in th...