• +49-(0)721-402485-12
Your experts for XML, XQuery and XML Databases

Where clause

Analogous to the SELECT-FROM-WHERE block in a SQL query, the where clause of XQuery enables the filtering of the data streams. If the expression of a where clause is evaluated with the current variable allocation to true, the execution of the return clause is initiated. Otherwise, the currently valid allocation is rejected. Within a where clause all variables introduced so far can (but do not have to) be referenced.

For example, the following query returns a list of all doctors and nurses of the hospital who will be retired in the next few years, which means they are at least 60 years old in the year 2004:

for $b in fn:doc("Hochwaldklinik.xml")//(Doctor | Nurse)
where $b/DateOfBirth < xs:date ("1944-01-01")
return
<MedicalPersonnel>
{$b/@Ward, $b/Name}
</MedicalPersonnel>

The result of the evaluation of a where clause corresponds to the effective Boolean value of the respective expression. By using the fn:boolean() function, the effective Boolean value can be explicitly determined for any value. During the determination of the Boolean value of the where clause, this function is implicitly used on the expression. So, the above where clause is evaluated internally as follows:

...
where fn:boolean($b/DateOfBirth < xs:date ("1944-01-01"))

Further possibilities of the filtering

In order to, for example, only output every tenth ambulant patient for a statistical survey, the modulo operation can be applied on the position variables:

for $p at $i in fn:collection("Patients")//Patient_ambulant
where $i mod 10 = 0
return
<Patient>{ $p/Name, $p/Anamnesis }</Patient>

Since a predicate is formed from expressions, all functions can be used in order to construct a filter condition for a where clause. The following FLWOR expression uses the fn:count() function for the determination of the number of the elements which are currently bound to the $x variable. Because of the application of the for clause and the resulting semantics, the return operator is never executed.

for $x in (1,2,3)
where fn:count ($x) > 1
return
<Text>This text will never appear</Text>

 

Source: "XQuery – Grundlagen und fortgeschrittene Methoden", dpunkt-Verlag, Heidelberg (2004)

<< backnext >>