Can we determine if the Salesforce instance is production org or a Sandbox org?

  • I am looking for the most efficient way of identifying the type of org (Production or Sandbox) via Apex code. URL scraping is not useful to me, since I'd like to get this information inside a trigger where URLs don't make sense.

    Thanks!

    If you are checking you'd better be sure your code is going to fully portable, ie it will work in any environment. I'm sure you've considered this already but thought it worth pointing out.

    You may want to change the accepted answer to use Daniel Hoechst's solution as it seems more current and useful.

    Yep, makes sense!

  • In Summer '14, (version 31.0), there is a new field available on the Organization object.

    SELECT IsSandbox FROM Organization LIMIT 1
    

    From the release notes under New and Change Objects:

    The Organization object has the following new read-only fields.

    • InstanceName
    • IsSandbox

    You can, for example, create a lazy loader that other classes can use like this:

    public Boolean runningInASandbox {
        get {
            if (runningInASandbox == null) {
                runningInASandbox = [SELECT IsSandbox FROM Organization LIMIT 1].IsSandbox;
            }
            return runningInASandbox;
        }
        set;
    }
    

    You can then call that as a Boolean value:

    if (!runningInASandbox()) {
      Messaging.SingleEmailMessage msg = new Messaging.SingleEmailMessage();
      msg.setSubject('An email');
      msg.setToAddresses(new List<String>{siteAdmin.Email});
      msg.setPlainTextBody('A message');
      Messaging.sendEmail(new List<Messaging.SingleEmailMessage>{msg});
    }
    

    Is this still the best answer? it's such a waste of a SOQL query to have to do it this way.

    AFAIK, yes. I haven't found any classes that provide this information. The closest I can find is ConnectApi.OrganizationSettings, but it doesn't look like it has any info about sandbox.

    Thanks for the confirmation, I keep thinking there has to be a metadata method that's been added by now. I suppose we could create our own custom metadata to track it

    Problem with custom metadata is remembering to flip it once a sandbox refreshes.

    Agreed, if you could have a script run on sandbox creation that did the query and populated the metadata that would work. I suppose you could create a class that did that, check for the metadata if it doesn't exist, run the query save the metadata that way the query would only run once for every org instance.

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM