The name FLWOR comes from the five clauses that make up a FLWOR expression: for
, let
, where
, order by
, and return
. Most of these clauses are optional: the only clause that is always present is the XQuery return
clause (though there must be at least one XQuery for
or let
clause as well). To see how FLWOR expressions work, we will build up our understanding one clause at a time.
Do remember that in a predicate, you select the item that you are testing relative to the context node, while in the where
clause, you select it using a variable name. A bare name such as genre
is actually selecting ./child::genre
- that is, it is selecting a child of the context node, which in this case is a <video>
element. It is very common to use such expressions in predicates, and it is very uncommon to use them (except by mistake!) in the where
clause. If you use a schema-aware processor like Saxon, then you might get an error message when you make this mistake; in other cases, it is likely that the condition will not select anything. The where
condition will therefore evaluate to false, and you will have to puzzle out why your result set is empty.
If there is no order by
clause in a FLWOR expression, then the order of the results is as if the for
clauses defined a set of nested loops. This does not mean they actually have to be evaluated as nested loops, but the result has to be the same as if they were. That is an important difference from SQL, where the result order in the absence of any explicit sorting is undefined. In fact, XQuery defines an alternative mode of execution, unordered mode, which is similar to the SQL rules. You can select this in the query prolog, and the processor might even make it the default (this is most likely to happen with products that use XQuery to search a relational database). Some products (Stylus Studio and Saxon among them) give you exactly the same result whether or not you specify unordered mode - since the XQuery specification says that in unordered mode anything goes, that is perfectly acceptable.
So, the return
clause might seem like the least significant part of the FLWOR, but a misplaced return can make a big difference in the result. Consider always aligning the F, L, O, W, and R clauses of a single FLWOR expression underneath each other, and indenting any nested expressions, so that you can see what is going on. You can do this easily with the Stylus Studio XQuery Editor.