XQuery Selecting and Filtering

Books.xml:




  
    ABC
    Author Name
    2020
    100.00
  

  
    XQuery Book
    Author 1
    Author 2
 2005
    300.00
  

  
    Ecosystem
    Author Name
 2010
    250.00
  

  
    Current Affairs
    Author Name
 2004
    500.00
  

  
    Science Book
    Author 1
    Author 2
    Author 3
 2011
    150.00
  


Selecting and Filtering Elements:

Using either a Path expression or with a FLWOR expression, we can select and filter the elements.

Example:

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

Explanation:

The above FLWOR expression includes:

  • for: It is used to bind a variable to each item returned by the in expression. It is optional.
  • let: It is optional.
  • where: It is used to specify criteria. It is optional.
  • order by: It is used to specify the sort order of the result. It is optional.
  • return: It is used to specify what to return in the result.

The for Clause:

To bind a variable to each item returned by the in expression, the for clause is used. This clause results in an iteration and we may use the to keyword to loop a specific number of times in a for clause. In a single FLWOR expression, multiple for clauses can be used.

Example 1:

for $x in (5 to 9)
return {$x}

Result:

5
6
7
8
9

Example 2:

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

Explanation:

In the above example, we are using the at keyword to count the iteration.

Result:

1. ABC
2. XQuery Book
3. Sociology 1
4. Current Affairs
5. Science Book

Example 3:

for $x in (1,2), $y in (10,20)
return x={$x} and y={$y}

Explanation:

In the above example, we are using multiple “in” expression in the for clause. We are separating each “in” in the expression with a comma.

Result:

x=1 and y=10
x=1 and y=20
x=2 and y=10
x=2 and y=20

The let Clause:

To allow the variable assignments, the let clause is used. It helps in avoiding the repeating of the same expression multiple times. It also does not result in an iteration.

Example:

let $x := (5 to 9)
return {$x}

Result:

5 6 7 8 9

The where Clause:

To specify one or more criteria for the result, the where clause is used.

Example:

where $x/price>200 and $x/price<400

The order by Clause:

To specify the sort order of the result, the order by clause is used.

Example:

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

Explanation:

In the above example, we are ordering the result by category and title.

Result:

ABC
XQuery Book
Current Affairs
Ecosystem
Science Book

The return Clause:

To specify what is to be returned, the return clause is used.

Example:

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

Result:

ABC
XQuery Book
Ecosystem
Current Affairs
Science Book