How to use CAML query to fetch data from a list?

Here is the CAML Query:



         <FieldRef Name="Title" />

         <Value Type="Text">title</Value>



I am using object model from my Webpart to load this CAML query and get the results back:

SPList list = web.Lists[“ListName”];

SPQuery spQuery = new SPQuery();

spQuery.Query = “” //CAML Query String from the Top;

SPListItemCollection items = list.GetItems(spQuery);

if (items != null)


if (items.Count > 0)


      … do something …



Works fine, isn’t it? Examine the CAML query carefully, I have not used <Query></Query> block in the Query.

Important Note:- Whenever you build a CAML Query and supply it to the SPQuery object make sure that the CAML query doesn’t have <Query></Query> block as starting and ending statement, otherwise SPQuery will always return empty result set. This is valid when we are using SPQuery object in the context of Web. If you are doing the same from a windows utility then <Query></Query> block should not create any issue.

Most developer face this issue first time they interact with CAML Query, hopping they find this blog useful.

Need help building CAML query? Visit this blog