Using CAML to query Sharepoint lists over Lookup fields

If you have ever tried to query a SharePoint List, over a LookupList value with CAML, you know that the "supposed" CAML way to do it is over the "Title" field of the LookupList values.

For example, if we want to query the sharepoint list, which has a Lookup field "ProjectID", and we want to extract all list items with the requested ProjectID, the CAML query would look like:

<Query>
<Where>
<Eq>
<FieldRef Name="ProjectID" />
<Value Type="Lookup">My Test Project 1</Value>
</Eq>
</Where>
</Query>

Of course, it is not very practical, and basicaly it is useless when developing SharePoint based applications: what if Project’s name changes? Or maybe we do not store the Project’s name in the "Title" field, but in some other text field?

The only solution would be by writing a CAML which would query the same list, but over ID of the Lookup list. Luckilly, there is a way to do that:

<Query>
<Where>
<Eq>
<FieldRef Name="ProjectID" LookupId="TRUE" />
<Value Type="Text">3</Value>
</Eq>
</Where>
</Query>

Now, this query will return the same results like the previous query, only that we query LookupList data over it’s ID, which is much more convinient. And, ListItem is really easy to retrieve from the SharePoint Object Model.