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
SFDC New learnerSFDC New learner 

Best way to retrieve recordtypes

Hi All,

What is the best way to write the code to retrieve the record type?
Below are the two ways 
1. ID rtId = [SELECT Id FROM RecordType WHERE sObjectType='Opportunity' AND Name='RT1'].Id;
2. Id rtId = Schema.SObjectType.Opportunity.getRecordTypeInfosByDeveloperName().get('RT1').getRecordTypeId();

Thanks!
Best Answer chosen by SFDC New learner
Sai PraveenSai Praveen (Salesforce Developers) 
Hi,

I would suggest the second option i'e below.
 
2. Id rtId = Schema.SObjectType.Opportunity.getRecordTypeInfosByDeveloperName().get('RT1').getRecordTypeId();

Because it does not require any SOQL query for retrival which will be efficient way .

Let me know if you face any issues.

If this solution helps, Please mark it as best answer.

Thanks,​​​​​​​

All Answers

Sai PraveenSai Praveen (Salesforce Developers) 
Hi,

I would suggest the second option i'e below.
 
2. Id rtId = Schema.SObjectType.Opportunity.getRecordTypeInfosByDeveloperName().get('RT1').getRecordTypeId();

Because it does not require any SOQL query for retrival which will be efficient way .

Let me know if you face any issues.

If this solution helps, Please mark it as best answer.

Thanks,​​​​​​​
This was selected as the best answer
mukesh guptamukesh gupta
Hi,

As per salesforce best practice we should follow second point. because 2nd point we don't need SOQL to fetch recordType that's will help tp breach the governer limit of SOQL that's fix 100.

To get a recordTypeId dynamically based on the developername of recordtype i.e API Name of RecordType
 
Id recordTypeId= Schema.SObjectType.Opportunity.getRecordTypeInfosByDeveloperName().get('RT1').getRecordTypeId();

System.debug('RecordTypeId=== '+recordTypeId);

if you need any assistanse, Please let me know!!

Kindly mark my solution as the best answer if it helps you.

Thanks
Mukesh

 
SFDC New learnerSFDC New learner
Thanks for your suggestions.