How to Write an SPQuery to Sort Your List

If you’re working with an SPListItemCollection, you might have the need to sort the data that stored in the collection. The best way I’ve found to do this is to build an SPQuery object and use that to actually query for the information. Using an object of this type makes it possible to send in whatever sort and/or orderby clause we’d like to use.

For example:

<OrderBy><FieldRef Name='EventDate' Ascending='FALSE'></FieldRef></OrderBy>

The full query would look something like this:

SPQuery oQuery = new SPQuery();
oQuery.Query = "<Where><Eq><FieldRef Name='AP_x0020__x002f__x0020_O'/>" +
"<Value Type='Text'>" + fruitName + "</Value></Eq></Where>" +
"<OrderBy><FieldRef Name='EventDate' Ascending='FALSE'></FieldRef></OrderBy>";

If you receive an error similar to:

One or more field types are not installed properly. Go to the list settings page to delete these fields.

Then you’ve set the FieldRef Name incorrectly. The trick to resolving this is:

  1. Navigate to your list that the column/field is contained within
  2. Click the New button as you normally would to create a new item in this list
  3. Click on View, Source from the toolbar in your browser window.
  4. Finally, do a find on the phrase fieldinternalname and locate the field you’re trying to query on
  5. Whatever value is stored in fieldinternalname is what you’ll want to use in your query

Any questions, let me know.

UPDATE: I recently discovered another trick to this. If you want to avoid having to seek out what the internal name of a particular field is, when you first name your column, do not include any spaces or special characters. Once the field (column) has been created, go back and rename the field to include the spaces or special characters as desired. SharePoint will still retain the original field name without spaces and you can use that directly in your query without issue.


4 Responses to “How to Write an SPQuery to Sort Your List”

  1. Pete January 13, 2012 at 3:05 am #

    Very handy – many thanks

  2. Deimos January 16, 2013 at 11:31 am #

    Your post was very useful to me. Thank you very much for sharing your knowledge.
    Also I like the layout of this blog – It’s very neat.

  3. hemanth August 6, 2014 at 7:11 am #

    I always had a issue with getting internal name of the list fields and replacing “%5d” with “_”.Now i follow the suggestion you given in update section.That is creating fields or coloumns without any space and later changing the title with proper space.

    Thank you very much for this information..

  4. Shereen Qumsieh September 11, 2014 at 4:27 am #

    Welcome! glad this has helped out!!

Leave a Reply