FLWORs
The basic structure of many (but not all) queries is the FLWOR expression. FLWOR (pronounced "flower") stands for "for, let, where, order by, return", the keywords used in the expression.
FLWORs, unlike path expressions, allow you to manipulate, transform, and sort your results. Example 1-5 shows a simple FLWOR that returns the names of all products in the ACC department.
Example 1-5. Simple FLWOR
Query for $prod in doc("catalog.xml")/catalog/product where $prod/@dept = "ACC" order by $prod/name return $prod/name Results <name language="en">Deluxe Travel Bag</name> <name language="en">Floppy Sun Hat</name>
As you can see, the FLWOR is made up of several parts:
-
for This clause sets up an iteration through the
productnodes, and the rest of the FLWOR is evaluated once for each of the four products. Each time, a variable named$prodis bound to a differentproductelement. Dollar signs are used to indicate variable names in XQuery.-
where This clause selects only products in the ACC department. This has the same effect as a predicate (
[@dept = "ACC"])in a path expression.-
order by This clause sorts the results by product name, something that is not possible with path expressions.
-
return This clause indicates that the
productelement'snamechildren should be returned.
The let clause (the L in FLWOR) is used to set the value of a variable. Unlike a for clause, it does not set up an iteration. Example 1-6 shows a FLWOR that returns the same result as Example 1-5. The second ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access