XQuery FLWOR Expressions

What is FLWOR?

“For, Let, Where, Order by, Return” together makes the acronym FLWOR (pronounced as “flower”).

  • For: To select a sequence of nodes.
  • Let: To bind a sequence to a variable.
  • Where: To filter the nodes.
  • Order by: To sort the nodes.
  • Return: To evaluate what to return, once for every node.

Books.xml:

<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
 
  <book category="Child">
    <title lang="en">ABC</title>
    <author>Author Name</author>
    <year>2020</year>
    <price>100.00</price>
  </book>
 
  <book category="IT">
    <title lang="en">XQuery Book</title>
    <author>Author 1</author>
    <author>Author 2</author>
 <year>2005</year>
    <price>300.00</price>
  </book>
 
  <book category="Sociology">
    <title lang="en">Sociology 1</title>
    <author>Author Name</author>
 <year>2010</year>
    <price>250.00</price>
  </book>
 
  <book category="GK">
    <title lang="en">Current Affairs</title>
    <author>Author Name</author>
 <year>2004</year>
    <price>500.00</price>
  </book>
 
  <book category="Science">
    <title lang="en">Science Book</title>
    <author>Author 1</author>
    <author>Author 2</author>
    <author>Author 3</author>
 <year>2011</year>
    <price>150.00</price>
  </book>
 
</bookstore>

To Select Nodes From “books.xml” With FLWOR:

Example 1:

doc("books.xml")/bookstore/book[price>250]/title

Explanation:

In the above example, we are using the predicate to select all the book elements under the bookstore element with a price element having a value higher than 250. Thus, the below will be extracted by the XQuery above:

Result:

<title lang="en">XQuery Book</title>
<title lang="en">Current Affairs</title>

Example 2:

for $x in doc("books.xml")/bookstore/book
where $x/price>250
return $x/title

Explanation:

In the above example, we are selecting all the book elements under the bookstore element with a price element having a value higher than 250 using the FLWOR. Thus, the below will be extracted by the XQuery above:

Result:

<title lang="en">XQuery Book</title>
<title lang="en">Current Affairs</title>

Example 3:

for $x in doc("books.xml")/bookstore/book
where $x/price>250
order by $x/title
return $x/title

Explanation:

In the above example, we are sorting the result using the FLWOR expression. Here, we are selecting all book elements under the bookstore element into a variable called $x, using the for clause. To select only book elements with a price element with a value greater than 250, we are using the where clause. Also, we are defining the sort-order, to sort by the title element, using the order by clause and specifying what should be returned, to return the title elements, using the return clause. Thus, the below will be extracted by the XQuery above:

Result:

<title lang="en">Current Affairs</title>
<title lang="en">XQuery Book</title>
Please Share