Using CAML query for SPQuery in Object Model

CAML queries are often used to query list items from a sharepoint list. There are many tools which are used to generate CAML queries which can be used in the Object Model (like webparts, controls, event receivers etc.,). Below is a sample <OrderBy> query generated from U2U CAML query builder.

  <FieldRef Name="Title" Ascending="FALSE"/>

While using a CAML query in the object model, the most common mistake done is to assign this CAML query as it is to the SPQuery.Query property. This doesn't reutrn any results!

The tags '<Query>' and '</Query>' shouldn't be used while assigning the CAML query to SPQuery.Query property. The query works if we remove the starting and ending <Query> element. Below is a sample code which used CAML query to order items by title.

using (SPWeb spWeb = SPContext.Current.Site.AllWebs["SubSite"])
    SPList spList = spWeb.Lists.TryGetList("Employees");
    SPQuery spQuery = new SPQuery();

    spQuery.Query = @"<OrderBy>
    <FieldRef Name=""Title"" Ascending=""FALSE""/>
    SPListItemCollection items = spList.GetItems(spQuery);

The SPQuery has many properties, like Query, RowLimit, ProjectedFields etc. Internally a CAML query is prepared using all these properties which will be within a <Query> element. So, in the object model we should only specify the actual query for the querying to work.