function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
IC-TannerIC-Tanner 

Avoiding double SOQL statement

When creating a variable from an SOQL query, it appears to be necessary to verify that there is a value to match up with the variable before trying to assign the value to it.  
 
For example, if I utilize the following code:
 workshopLeadRTID = [Select Id from RecordType where SobjectType='lead' and Name=:'Workshop Lead'].id; 
If no value is found via the SOQL query, I receive a runtime error when what I want is to have no value assigned to the variable without the error. Therefore I normally run two queries below:
 
//determine if a value is found based on the query
integer workshopLeadRTID_count = [Select count() from RecordType where SobjectType='lead' and Name=:'Workshop Lead'];
 
//if a value is found, assign it to the variable.  
  if (workshopLeadRTID_count > 0)
  {
  workshopLeadRTID = [Select Id from RecordType where SobjectType='lead' and Name=:'Workshop Lead'].id; 
  }
 
It seems to me that there must be a better way of doing this that I am not seeing to avoid having to do 2 SOQL queries instead of just 1. Any suggestions? thanks! 
Best Answer chosen by Admin (Salesforce Developers) 
mtbclimbermtbclimber

Yes, assign it to a list first:

 

 

List<RecordType> recordTypes = [Select Id from RecordType where SobjectType='lead' and Name=:'Workshop Lead'];

 

 

 

By the way, there is another mechanism to get recordtype information:

 

 

List<Schema.RecordTypeInfo> leadRecordTypeInfos = Lead.SobjectType.getDescribe().getRecordTypeInfos();

 

 

This saves the query but counts against the recordtypeinfo call limit though you might find it more valuable as it provides more info than the query does, specifically whether it's available for the user and whether it's the default.

 

Check out the Apex Language Reference for more info.

Message Edited by mtbclimber on 02-26-2009 09:02 AM

All Answers

mtbclimbermtbclimber

Yes, assign it to a list first:

 

 

List<RecordType> recordTypes = [Select Id from RecordType where SobjectType='lead' and Name=:'Workshop Lead'];

 

 

 

By the way, there is another mechanism to get recordtype information:

 

 

List<Schema.RecordTypeInfo> leadRecordTypeInfos = Lead.SobjectType.getDescribe().getRecordTypeInfos();

 

 

This saves the query but counts against the recordtypeinfo call limit though you might find it more valuable as it provides more info than the query does, specifically whether it's available for the user and whether it's the default.

 

Check out the Apex Language Reference for more info.

Message Edited by mtbclimber on 02-26-2009 09:02 AM
This was selected as the best answer
IC-TannerIC-Tanner
Thanks for the suggestions! I wasn't aware of the recordtypeinfo call.