I am trying to fix

'Too many SOQL Queries Limit'

and wanted to implement static util methods to cache the SOQL Query results so that the query with the same condition is not queried multiple times. Here is my query:

[Select id, name From Profile Where id=: userInfo.getProfileId()];

How do i implement static util method to cache this query result?


You can use a static variable in a helper class to cache the result while running a single transaction.

public class UserProfileHelper {

   private static Profile userProfile;
   public static Profile getProfile() {
      if (userProfile == null) userProfile = [select Id, Name from Profile 
              where Id = :userInfo.getProfileId()];
      return userProfile;

  • For example, if this code is executed for user1 first time and then user2 second time and then user1 again, would this utility class cache the results of user1? I was thinking of using a Map to store <Id, Profile>& caching it – Shalini SF Apr 9 '15 at 1:48
  • Not really, it is going to query the profile once in a single transaction, so two users are not sharing the same code execution. It is useful in the situations where you have one trigger that checks a users profile and then another trigger that gets fired at the same time (or cascade to another object) and that trigger needs the profile again. It is not like a mem-cache or session storage. – CyberJus Apr 9 '15 at 2:26

1) You can use the global variable "Useinfo.getProfileId()" if you only need profile id.

2) You can use static variable to cache profile you query. see code:

public static Profile CachingProfile;

public constructor method(){
    CachingProfile = [Select id, name From Profile Where id=:userInfo.getProfileId()];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.