Search code examples
salesforcesoql

Salesforce SOQL - DefaultDivision with User info


I'm trying to write a SOQL query that pulls back User information along with the DefaultDivision's name. When executing the following:

Select u.Email, u.FirstName, u.LastName, u.DefaultDivision from User u

the value for 'DefaultDivision' is an Id (like 02d3498202020222) instead of the friendly name (like North America). I know that the DefaultDivision maps to the Division object's Id, but how do I get the name?

I have tried things like:

select u.Email, (select Name from Division where Id = u.DefaultDivision) from User u

but that doesn't work because there is no direct relationship (and yet, there is...!).


Solution

  • Unlike SQL, SOQL does not support subqueries of the type you have given there.

    In most cases with SOQL where there is an explicit relationship defined, you can query data from that explicit relationship directly, like

    select u.Email, u.DefaultDivision.Name from User u where Id=blahblahblah
    

    However there are some cases where such a relationship is not explicitly defined, and I believe DefaultDivision is one of those (so in fact my query above probably will not work). When this is the case, there's no single-query way to get the information you want -- you'll have to first query on divisions and their IDs, then query users with their DefaultDivision, and then resolve the division names from the IDs using the results of the first query.

    Fortunately this type of situation doesn't happen very often anymore, but in using Divisions you're plumbing the depths of Salesforce.com a bit so you may find some unusual stuff there.