
This page contains samples of FLWOR expressions. FLWOR expressions are named for the "for", "let", "where", "order by" and "return" clauses that make up these expressions. A simple explanation of FLWOR expressions is that the "for" and "let" clauses bind values to variables, the "where" clause filters these bindings by some condition, the "order by" clause orders the surviving bindings based on some item, and the return clause puts together a result based on the bindings to be returned as the result of the expression. Here are some examples that demonstrate this type of expression.
{-- Simple FLWOR expression
List the item number and description of all bicycles --}
<Bicycles>
{
for $i in document("data/R-items.xml")//item_tuple
where
contains($i/description, "Bicycle")
return
<bicycle>
{ $i/itemno }
{ $i/description }
</bicycle>
}
</Bicycles>
{-- FLWOR expression combining information from multiple
documents
List all aution item's item no, description, price, bid
date, and the bidder's name from 3 different
documents --}
for $u in document("data/R-users.xml")//user_tuple,
$b in document("data/R-bids.xml")//bid_tuple[userid =
$u/userid],
$i in document("data/R-items.xml")//item_tuple[itemno =
$b/itemno]
return
<item>
{
$i/itemno,
$i/description,
$b/bid_date,
$u/name
}
</item>
sortby(itemno)
{-- An "outer join" is a join that preserves information
from one or more of the participating sources, including
elements that have no matching element in the other
source.
List all users, and for each user, list its bidding
item, bidding price, and date
Note in the result, user U06 has no matching bids --}
for $u in document("data\R-users.xml")//user_tuple
return
<user id={$u/userid}>
{$u/name}
{
for $b in document("data\R-bids.xml")//bid_tuple
where $u/userid = $b/userid
order by $b/itemno
return
<bids>
{$b/itemno}
{$b/bid_date}
{$b/bid}
</bids>
}
</user>
{-- where clause contains multiple conditions
List all items on auction whose reserved price is less
than 100 and order them by reserve_price
The inner where clause tests for two conditions --}
let $i := distinct(document("data\R-bids.xml")//bid_tuple/itemno),
$j := document("data\R-items.xml")//item_tuple
return
<auction_items>
{
for $i in $i, $p in $j
where $p/itemno=$i and ($p/reserve_price<100)
order by $p/reserve_price
return
<item id={$i}>
{$p/description}
{$p/reserve_price}
</item>
}
</auction_items>
{-- List all items on auction
The outer FLWR does not have a for clause. $i binds to
the node set returned by the distinct() function
In the inner for clause, for $i in $i, each time $i
binds to a node in the node set assigned to $i in the
outer let clause
Demonstrates variable scoping in nested FLWOR
expressions --}
let $i := distinct(document("data\R-bids.xml")//bid_tuple/itemno)
return
<auction_items>
{
for $i in $i
for $p in document("data\R-items.xml")//item_tuple[itemno=$i]
return
<item id={$i}> { $p/description/text() } </item>
}
</auction_items>