[SalesForce] Need to run soql as admin in apex controller

I need to run an SOQL command, as admin just like system.runAs(u) in controller.

Is there a way to do this.

Best Answer

To run a query as "an administrator", use the "without sharing" keyword within a class:

public without sharing class Utility {
    public static Account[] queryAccounts() {
        return [SELECT Id, Name, Industry FROM Account LIMIT 100];

While you are still running the query as the current user, the current user's sharing is ignored, which means that the query will execute as if the user were an administrator.

Also note that within triggers, the code runs by default "without sharing", so it is generally not necessary to run "as administrator" unless you're using utility classes (such as the example here).

Related Topic