SPQuery Returns All of the Items

During a development project, calling SPQuery returned all items from list! Looks like it just ignored the filters we applied.

SPList list = new SPSite("https://MySharePointSite").OpenWeb().Lists[listName];

SPQuery query = new SPQuery();
query.Query = "<Query><Where><Eq><FieldRef Name="Title" /><Value Type="Text">Test</Value></Eq></Where></Query>";
SPListItemCollection items = list.GetItems(query);

Fix:

This above code returns all items in the list, but if you remove the <Query> tag all works fine: “<Query><Where><Eq><FieldRef Name=”Title” /><Value Type=”Text”>Test</Value></Eq></Where></Query>“; 

SPList list = new
SPSite("https://MySharePointSite").OpenWeb().Lists[listName];

SPQuery query = new SPQuery();

query.Query = "<Where><Eq><FieldRef Name="Title" /><Value Type="Text">Test</Value></Eq></Where>"; 
SPListItemCollection items = list.GetItems(query);

Remember, Query XML is case sensitive! So <Where> is not equal to <where>.

Salaudeen Rajack

Salaudeen Rajack - Information Technology Expert with Two-decades of hands-on experience, specializing in SharePoint, PowerShell, Microsoft 365, and related products. He has held various positions including SharePoint Architect, Administrator, Developer and consultant, has helped many organizations to implement and optimize SharePoint solutions. Known for his deep technical expertise, He's passionate about sharing the knowledge and insights to help others, through the real-world articles!

One thought on “SPQuery Returns All of the Items

  • the code is working, but it is not retrieving all items because of the value .

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *