SOQL Governor Limits

Since Salesforce has a multi-tenant cloud architecture, the Salesforce platform has to put some limitations 😭 to prevent a single tenant from monopolizing the database servers CPU and affecting the performance for all the other tenant. That is how Salesforce is able to support millions of users.

Maximum number of records retrieved in a single transaction

The maximum no of records that can be retrieved in a SOQL query are 50,000. If more than 50,000 records are returned, an error is thrown.

To avoid this error, we should apply appropriate filters with WHERE clause to limit the number of records returned with the LIMIT clause.

Maximum length of SOQL statements

The maximum length of a SOQL statement is 20,000 characters. If there are more characters, an error: “Query too Complicated” is returned.

Maximum number of SOQL queries in a single transaction

If the number of SOQL queries running in a single transaction exceeds 100, the very common “Too many SOQL queries: 101” is thrown. To avoid these this error, we should avoid performing SOQL queries inside for loop.

For example:

List<Contact> conList = new List<Contact>();
List<String> emailsToFind;
for(String str :namesToFind){
  Contact con = [SELECT Id, Name FROM contact WHERE name= :str];

Here if we are finding more than 100 names, “Too many SOQL queries: 101” error will be returned, as for every name to find, we are using a separate query.

To solve we can use the IN operator in this case:

List<Contact> conList = [Select Id,Name
  FROM Contact
  Where Name IN :namesToFind];

As a rule, never perform SOQL queries inside for loops.