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

I have two Objects object1 & object2.

In object1 there is a field, field1 with Lookup to object2. Now what I need to do is query object2 fields based on the id of field1 How can I perform this query?

share|improve this question
up vote 2 down vote accepted


Let say you know the Id of Object1. So you can read the Field1__c from that Object1 - this will be Id of the Object2.

Id idOfObject2 = [ Select Field1__r.Id From Object1 Where Id = :someVar ].Field1__r.Id;

Now we reading Object2 fields:

Object2 obj2 = [ Select Field1__c, Field2__c From Object2 Where Id = :idOfObject2 ];

Or we can do the same simpler:

Object2 obj2 = [ Select Field1__c, Field2__c From Object2 
                 Where Id IN (Select Field1__c From Object1 Where Id = :someVar) ];

I think you can do it like this:

Select Id, Name From Object2 Where Id = :Object1.field1__c

You can read more about lookup relationships at the official doc site: Relationship Queries

share|improve this answer
I can't go with the second one because all my fields are in object2,so need to query object2....and for the first one getting error as Compile Error: Variable does not exist: object1__r.field1__c – Eagerin Sf Dec 13 '12 at 8:02
What is your key? I mean - based on which id you are reading the data? – Sergey Utko Dec 13 '12 at 8:06
Thats Perfect...Thanks – Eagerin Sf Dec 13 '12 at 8:27

You can also do this thriugh one single query -

[Select  Field2__r.Field2_field__c FROM Object1 obj where = :Object1ID];
share|improve this answer

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.