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

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});
}

It's not perfect but the static method

System.URL.getSalesforceBaseUrl()

Will allow you to scrape the instance name, will that be sufficient to distinguish between production and sandbox?


Michael Farrington recently posted an Apex method for this on his blog: http://www.michaelforce.org/recipeView?id=a0Ga000000Ekp65EAB

This method uses URL.getSalesforceBaseUrl().getHost() which should work in a trigger.