<bookstore>
{ for $b in document('bookstore')/bookstore/book
where $b/@genre='philosophy' and $b/@publicationdate='1991'
return $b/title }
{ for $b2 in document('bookstore2')/bookstore/book
where $b2/@genre='philosophy' and $b2/@publicationdate='2002'
return $b2/title }
</bookstore>
3.9 Unordered Expressions
In general, XQuery expressions return sequences that have a well-defined order. For example, the result of an axis step in a path expression is always returned in document order. Similarly, the result of a FLWOR expression is ordered by its order by clause and/or the expressions in its for clauses. However, in some expressions, the order of the result may not be significant to the user. In such an expression, one ordering may be much more efficient to materialize than another, and a significant performance advantage may be realized by allowing the system to materialize the results of the expression in the order it finds most efficient. XQuery provides a function named fn:unordered for this purpose.
The fn:unordered function takes any sequence of items as its argument, and returns the same sequence of items in a nondeterministic order. A call to the fn:unordered function may be thought of as giving permission for the argument expression to be materialized in whatever order the system finds most efficient. The fn:unordered function may be applied to the result of a query or to a subexpression inside a query.
The use of the fn:unordered function is illustrated by the following example, which joins together two documents named parts.xml and suppliers.xml. The example returns the part numbers of red parts, paired with the supplier numbers of suppliers who supply these parts. If the fn:unordered function were not used, the resulting list of (part number, supplier number) pairs would be required to have an ordering that is controlled primarily by the document order of parts.xml and secondarily by the document order of suppliers.xml. However, this might not be the most efficient way to process the query if the ordering of the result is not important. An XQuery implementation might be able to process the query more efficiently by using an index to find the red parts, or by using suppliers.xml rather than parts.xml to control the primary ordering of the result. The fn:unordered function gives the query evaluator freedom to make these kinds of optimizations.
fn:unordered(
for $p in fn:doc("parts.xml")//part[color = "Red"],
$s in fn:doc("suppliers.xml")//supplier
where $p/suppno = $s/suppno
return
<ps>
{ $p/partno, $s/suppno }
</ps>
)