<Where>
<Eq>
<FieldRef Name=”FieldName” />
<Value Type=”DataType”>Value</Value>
</Eq>
</Where>
<OrderBy>
<FieldRef Name=”FieldName” />
<FieldRef Name=”FieldName” />
</OrderBy>
</Query>
Operators in CAML Query
From the above structure, we came to know that it uses Where and OrderBy elements to retrieve the data from the list.
Let us know about the operators present in the CAML query and its usage:
Inside the Where element
1. Logical Operators - AND, OR
2. Comparison Operators - Listed Below in the table
AND – Which takes two conditions are satisfied
OR – Which takes when either of the conditions is satisfied
Comparison Operators
Inside the OrderBy/GroupBy element
OrderBy – Which orders or sort the data depends upon the field (FieldRef element) given.
GroupBy – Which groups the data depends upon the group by field (FieldRef element) given.
Examples
Logical & Comparison Operators
Use of AND, Gt, Leq
<Query>
<Where>
<And>
<Gt>
<FieldRef Name="Quantity" />
<Value Type="Number">0</Value>
</Gt>
<Leq>
<FieldRef Name="Price" />
<Value Type="Number">2000</Value>
</Leq>
</And>
</Where>
</Query>
Use of OR, Gt, Leq
<Query>
<Where>
<Or>
<Gt>
<FieldRef Name="Quantity" />
<Value Type="Number">0</Value>
</Gt>
<Leq>
<FieldRef Name="Price" />
<Value Type="Number">2000</Value>
</Leq>
</Or>
</Where>
</Query>
Use of BeginsWith, Leq
<Query>
<Where>
<And>
<BeginsWith>
<FieldRef Name="Title" />
<Value Type="Text">M</Value>
</BeginsWith>
<Leq>
<FieldRef Name="Quantity" />
<Value Type="Number">1000</Value>
</Leq>
</And>
</Where>
<OrderBy>
<FieldRef Name="Price" Ascending="False" />
</OrderBy>
</Query>
OrderBy Operator
<Query>
<Where>
<Or>
<Gt>
<FieldRef Name="Quantity" />
<Value Type="Number">0</Value>
</Gt>
<Leq>
<FieldRef Name="Price" />
<Value Type="Number">2000</Value>
</Leq>
</Or>
</Where>
<OrderBy>
<FieldRef Name="Price" Ascending="True" />
</OrderBy>
</Query>
Is it possible to write this queries without any errors manually?
Yes. But we will know the errors only after executing the program. Hence there is a free CAML query builder which will generate the query easily.
To know about where to download and how to use the CAML Query builder read this article.
To know how to use the CAML query in the Microsoft Visual Studio read this article.