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 product nodes, and the rest of the FLWOR is evaluated once for each of the four products. Each time, a variable named $prod is bound to a different product element. 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 product element's name children 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 line is a let clause that assigns the product element's name child to a variable called $name. The $name variable is then referenced later in the FLWOR, in both the order by clause and the return clause.

Example 1-6. Adding a let clause

for $product in doc("catalog.xml")/catalog/product
let $name := $product/named
where $product/@dept = "ACC"
order by $name
return $name

The let clause serves as a programmatic convenience that avoids repeating the same expression multiple times. Using some implementations, it can also improve performance, because the expression is evaluated only once instead of each time it is needed.

This chapter has provided only very basic examples of FLWORs. In fact, FLWORs can become quite complex. Multiple for clauses are permitted, which set up iterations within iterations. In addition, complex expressions can be used in any of the clauses. FLWORs are discussed in detail in Chapter 6. Even more advanced examples of FLWORs are provided in Chapter 9.

Get XQuery now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.