Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

XQuery selection and filtering

May 28, 2021 XQuery

Table of contents

XQuery selects and filters

This section describes how to select and filter elements in XQuery.

XML instance documentation

We'll continue to use this "books.xml" document in the following example (the same XML file used in the previous section).

View the "books" file .xml your browser.

Select and filter elements

As we saw in the previous section, we use path expressions or FLWOR expressions to pick and filter elements.

Take a look at the following FLWOR expression:

for $x in doc("books.xml")/bookstore/book
where $x/price>30
order by $x/title
return $x/title
  • for - (optional) bundles a variable to each item returned by the in expression
  • let - (optional)
  • Where - (optional) set a condition
  • Order by - (optional) sets the order in which the results are arranged
  • return - specifies what is returned in the results

The for statement

The for statement bundles variables to each item returned by the in expression. T he for statement produces iterations. Multiple for statements can exist in the same FLWOR expression.

To cycle a specified number of times in a for statement, you can use the keyword to:

for $x in (1 to 5)
return <test>{$x}</test>



The keyword at can be used to calculate iterations:

for $x at $i in doc("books.xml")/bookstore/book/title
return <book>{$i}. {data($x)}</book>


<book>1. Everyday Italian</book>
<book>2. Harry Potter</book>
<book>3. XQuery Kick Start</book>
<book>4. Learning XML</book>

Multiple in expressions are also allowed in the for statement. Use a comma to split each in expression:

for $x in (10,20), $y in (100,200)
return <test>x={$x} and y={$y}</test>


<test>x=10 and y=100</test>
<test>x=10 and y=200</test>
<test>x=20 and y=100</test>
<test>x=20 and y=200</test>

let statement

The let statement completes the variable assignment and avoids repeating the same expression multiple times. The let statement does not cause iterations.

let $x := (1 to 5)
return <test>{$x}</test>


<test>1 2 3 4 5</test>

Where statement

Where statements are used to set one or more criteria (criteria) for the result.

where $x/price>30 and $x/price<100

Order by statement

The order by statement is used to specify the sort order of the results. Here, we sort the results by category and title:

for $x in doc("books.xml")/bookstore/book
order by $x/@category, $x/title
return $x/title


<title >Harry Potter</title>
<title >Everyday Italian</title>
<title >Learning XML</title>
<title >XQuery Kick Start</title>

Tip: You can also learn about SQL ORDER BY keywords!

Return statement:

The return statement specifies what to return.

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


<title >Everyday Italian</title>
<title >Harry Potter</title>
<title >XQuery Kick Start</title>
<title >Learning XML</title>