You need to sign in to do that
Don't have an account?
brhunt
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
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
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
Can you try below query.
Thanks,
Vinay Kumar
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
And the idea of using lastmodifiedby was brilliant. I believe that will accomplish what I need instead of just using owner.
Thanks.
Bryan Hunt
The SOQL query you shared is close to being correct. However, since the OwnerId field in the Lead object is a reference to the User object, you need to use a relationship query to fetch the related User's CompanyName. Here's the updated query:
SELECT Id, Name, OwnerId, Owner.CompanyName
FROM Lead
LIMIT 10
In this query, Owner represents the relationship name between the Lead and User objects. By using dot notation (Owner.CompanyName), you can access the CompanyName field of the related User.
Please note that the Owner field in the Lead object is a polymorphic field, meaning it can refer to both User and Queue objects. So, if you want to only fetch the CompanyName for User owners, you can add a WHERE clause to filter the results:
SELECT Id, Name, OwnerId, Owner.CompanyName
FROM Lead
WHERE Owner.Type = 'User'
LIMIT 10
This WHERE clause ensures that only Lead records with User owners are included in the result set. I hope this guide from smash karts (https://smashkartsio.com) helps! Let me know if you have any further questions.