Sharepoint - CAML viewfields

<ViewFields> is used in the CAML query to define that how many fields you want to retrieve by executing the query. If we did not define <ViewFields> then it will retrieve all the columns of list.

For example if I define ViewFields like:

<ViewFields>
    <FieldRef Name="ID"></FieldRef>
    <FieldRef Name="Title"></FieldRef>
</ViewFields>

then it will retreive only two columns ID & Titile from the list.

It's not mandatory to set <ViewFields>.

Read more: SPQuery.ViewFields Property


  • ViewFields basically gives you option to reduce data in response.
  • It allows you to specify which fields you want in return for your query.

It is always a best practice to use ViewFields as and when possible.

Also in conjunction with SPQuery.ViewFields you must use SPQuery.ViewFieldsOnly, then only it will return only those column, else it is going to return all column in response.

For Ex:

SPQuery query = new SPQuery();

query.Query = <<YOUR QUERY GOES HERE>>
query.ViewFields = "<ViewFields>"+
    "<FieldRef Name="ID"></FieldRef>"+
    "<FieldRef Name="Title"></FieldRef>"+
"</ViewFields>";

query.ViewFieldsOnly = true; 

Tags: