Welcome to our XQuery FLWOR Expressions tutorial! Today, we'll dive into one of the most powerful and flexible features of XQuery - the FLWOR (For, Let, Where, Order By, and Return) expression. 📝
FLWOR expressions are a combination of five keywords (For, Let, Where, Order By, and Return) that help you to navigate and manipulate XML data. They allow you to perform complex operations, such as filtering, sorting, and joining data, just like you would in a programming language.
The for clause is used to iterate through the XML document. It defines a variable to hold the current node and loops through each node in the specified path.
for $node in //bookIn the above example, $node will iterate through all book elements in the XML document.
The let clause is used to create temporary variables. It allows you to perform calculations, store intermediate results, and reuse them later in the expression.
let $total := count($node)
for $node in //book
return $node/titleIn the above example, we've created a variable $total that stores the total number of book elements in the document. We then loop through each book element and return the title of each book.
The where clause is used to filter the results based on a condition. It's similar to the SQL WHERE clause.
for $book in //book[price > 10]
return $book/titleIn the above example, we're only considering the book elements where the price is greater than 10 and returning their titles.
The order by clause is used to sort the results. It can be used with both numeric and string data.
for $book in //book
order by $book/price
return $book/titleIn the above example, we're sorting the book elements by their price and returning their titles.
The return clause specifies the result of the FLWOR expression. It determines what data will be output.
for $book in //book
order by $book/price
return <result>
<title>{$book/title}</title>
<price>{$book/price}</price>
</result>In the above example, we're returning a result element for each book element, containing both the title and price.
Let's write a FLWOR expression that calculates the average price of books in an XML document.
let $totalPrice := 0
for $book in //book
let $bookPrice := $book/price
if ($bookPrice > 10) then
$totalPrice += $bookPrice
return $totalPrice / count(//book)In this example, we're initializing a variable $totalPrice to 0. We then loop through each book element and, if the price is greater than 10, we add the price to the total. Finally, we return the average price by dividing the total by the total number of books.
What does the `for` clause do in a FLWOR expression?
What is the purpose of the `let` clause in a FLWOR expression?