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:




  
    ABC
    Author Name
    2020
    100.00
  

  
    XQuery Book
    Author 1
    Author 2
 2005
    300.00
  

  
    Sociology 1
    Author Name
 2010
    250.00
  

  
    Current Affairs
    Author Name
 2004
    500.00
  

  
    Science Book
    Author 1
    Author 2
    Author 3
 2011
    150.00
  


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:

XQuery Book
Current Affairs

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:

XQuery Book
Current Affairs

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:

Current Affairs
XQuery Book