XQuery has an expression called a FLWOR expression, which is similar to a SQL Select statement that that has From and Where clauses. FLWOR is pronounced "flower", and is an acronym for the keywords used to introduce each clause (for, let, where, order by, and return).
Here is a FLWOR expression that returns holdings for AMZN.
for $h in collection('holdings')/holdings
where $h/stockticker = 'AMZN'
order by $h/shares
return $h
In the preceding query, the FLWOR expression performs the following functions:
- The for clause binds the variable $h to each holdings element.
- The where clause filters out bindings of $h for which the stockticker element does not contain the value AMZN.
- The order by clause determines the order.
- The return clause produces a result for each binding of $h.
FLWOR expressions are frequently used to combine related information. The possible combinations are generated by using variables in the for clause and using a where clause to filter out combinations that are not useful. This is known as a "join". Consider the following expression:
for $u in collection('users')/users,
$h in collection('holdings')/holdings
where $u/userid=$h/userid
order by $u/lastname, $u/lastname
return
<holding>
{
$u/firstname,
$u/lastname,
$h/stockticker,
$h/shares
}
</holding>
This expression finds every pair of users elements and holdings elements whose userid child element has the same value, and then builds a holding element that describes the user and his holdings.
Now, let's look at a FLWOR expression that uses a let clause:
let $h := collection('holdings')/holdings
return count($h)
A let clause binds a variable to a sequence, which often contains more than one item. In the preceding query, $h is bound to all of the holdings elements in the collection, and the return clause is evaluated. Note the difference between a for clause and a let clause: A for clause always iterates over a sequence, binding a variable to each item; a let clause simply binds a variable to the entire sequence.
In the preceding expression, the result is 8
. In contrast, if you use the following for clause:
for $h in collection('holdings')/holdings
return count($h)
The result is a sequence of numbers: 1 1 1 1 1 1 1 1
.
In some cases, you may find it useful to combine for and let clauses. In the following expression, these two clauses are combined to produce a result that counts the number of stock holdings for each user.
for $u in collection('users')/users
let $h := collection('holdings')/holdings[userid=$u/userid]
order by $u/lastname, $u/firstname
return
<user nstocks="{count($h)}">
{
$u/firstname,
$u/lastname
}
</user>