Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Sorry if this has been asked before, but I feel that there has to be a simpler way to get a User field from the Owner relationship.

I'm currently looping through 2 lists and then mapping the objects together:

Map<Opportunity, User> oppMapping = new Map<Opportunity, User>();
List<User> userList = [SELECT Id, Custom_field__c FROM User];
List<Opportunity> oppList = [SELECT Id, OwnerId FROM Opportunity];

for(Opportunity opp : oppList){
    for(User user : userList){
        if(opp.OwnerId == user.Id){
            oppMapping.put(opp, user);

//Retrieve custom user field from Opportunity
for(Opportunity opp){

Ideally it would be great if I could just do something like: SELECT Id, Owner.Custom_field__c FROM Opportunity, but I know that's not possible.

share|improve this question
up vote 3 down vote accepted

Your query:

SELECT Id, Owner.Custom_field__c FROM Opportunity

is valid (assuming you have added Custom_field__c to User) and is the simplest way to query the data as the relationship is then already present in the returned objects.


It is not necessary here, but if you did need to write code to relate one object to another it is important to avoid doubly nested loops because they cause execution time to grow exponentially. So your code might work fine to start with but then one day when there is enough data you'll hit a governor limit (and probably in production).

This is a common pattern to use (using a map) that results in linear not exponential execution time growth (and only queries the necessary User objects not all of them):

Set<Id> userIds = new Set<Id>();
for (Opportunity opp : oppList) {
Map<Id, User> users = new Map<Id, User>([
        select Id, Custom_field__c
        from User
        where Id in :userIds
for (Opportunity opp : oppList) {
    Object o = users.get(opp.Id).Custom_field__c;
share|improve this answer
Ahh... nevermind spelled Opportunity wrong in the query I was using. Glad that was easy. – Matthew Mitchener May 16 '14 at 15:23
Also thanks for the helpful tip on double loops! Performance and governor limits was one of the main reasons I was asking. – Matthew Mitchener May 16 '14 at 15:32
@MatthewMitchener No problem. Relationship queries (…) are a big help for keeping code simpler, but I know from (painful personal) experience that when you have to write code that relates objects together it needs to be done with care. – Keith C May 16 '14 at 15:53

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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