+ Start a Discussion
brhuntbrhunt 

SOQL query to return some Lead data, along with the Lead Owner's CompanyName

Hello,

I am trying to write a SOQL query to return some Lead data, along with the Lead Owner's CompanyName.

I have tried multiple iterations, but cannot seem to get the syntax right.

Something like this:

select Id, Name, OwnerId, (select Id, CompanyName from User where Id =: OwnerId)
from Lead 
limit 10

Thanks for any help that you can give.

Bryan Hunt
Best Answer chosen by brhunt
brhuntbrhunt
David, thanks for the reply.  I knew that CompanyName could be referenced by the dot operator, but until I read your post I never understood why.

And the idea of using lastmodifiedby was brilliant.  I believe that will accomplish what I need instead of just using owner.

Thanks.

Bryan Hunt

All Answers

VinayVinay (Salesforce Developers) 
Hi Bryan,

Can you try below query.
 
SELECT Id, Name, OwnerId, Owner.CompanyName From Lead

Thanks,
Vinay Kumar
David Zhu 🔥David Zhu 🔥
I am afraid you cannot get the company name along with other fields in one query.
Owner field is a lookup field to User and Group object. Since Group does not have ComanyName field,  query with Owner.CompanyName will fail.

You may refer the code snippet below:

Lead lead =[Select Id, Name, OwnerId, Owner.Name From Lead where id = 'xxxxxxx' limit 1];

if (lead.ownerid.startsWith('005'))
{
    User  u = [Select Id,CompanyName from user where id =:lead.ownerId Limit 1];
     //get company nam by u.CompanyName.
}

A side topic, you can get the lastmodified and createdby user's company name by one soql query as those two fields are lookup to User object.

select id, name, LastModifiedBy.id, LastModifiedBy.name, LastModifiedBy.CompanyName from lead
brhuntbrhunt
David, thanks for the reply.  I knew that CompanyName could be referenced by the dot operator, but until I read your post I never understood why.

And the idea of using lastmodifiedby was brilliant.  I believe that will accomplish what I need instead of just using owner.

Thanks.

Bryan Hunt
This was selected as the best answer
brhuntbrhunt
Done.