An assignment of the variables used in the for and let clauses of a query is called tuple. The tuples generated by a query can be filtered with the where clause and sorted with the order by clause. For instance, the following query outputs only the open auctions with a number of bidders between 1 and 3:
for $a in doc("auction.xml")/site/open_auctions/open_auction
let $b := $a/bidder
where count($b) >= 1 and count($b) <= 3
return <auction id = "{$a/@id}">
<bidder_count>{count($b)}</bidder_count>
</auction>
The next query sorts the open auction with respect to the number of auction bidders:
for $a in doc("auction.xml")/site/open_auctions/open_auction
let $b := $a/bidder
order by count($b)
return <auction id = "{$a/@id}">
<bidder_count>{count($b)}</bidder_count>
</auction>
More than one sort key can be used, separated by a comma. By default, the ordering is ascending. A descending ordering can be obtained by adding the keyword descending after the corresponding sort key. An instance follows:
for $a in doc("auction.xml")/site/open_auctions/open_auction
let $b := $a/bidder
order by count($b) descending, number($a/current)
return <auction id = "{$a/@id}">
<bidder_count>{count($b)}</bidder_count>
{$a/current}
</auction>