O'Reilly logo

XQuery, 2nd Edition by Priscilla Walmsley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 7. Sorting and Grouping

This chapter explains how to sort and group data from input documents. It covers sorting in FLWORs, grouping results together, and calculating summary values by using aggregate functions.

Sorting in XQuery

Path expressions, which are most often used to select elements and attributes from input documents, always return items in document order. FLWORs by default return results based on the order of the sequence specified in the for clause, which is also often document order if a path expression was used.

You can sort data in an order other than document order by using the order by clause of the FLWOR. Therefore, in some cases it is necessary to use a FLWOR where it would not otherwise be necessary. For example, if you simply want to select all your items from an order, you can use the path expression doc("order.xml")//item. However, if you want to sort those items based on their num attribute, the most straightforward way to do this is using a FLWOR with an order by clause. The other alternative is to use the sort function, described in “The sort Function”.

The order by Clause

Example 7-1 shows an order by clause in a FLWOR.

Example 7-1. The order by clause
for $item in doc("order.xml")//item
order by $item/@num
return $item

The results will be sorted by item number. The syntax of an order by clause is shown in Figure 7-1.

The order by clause is made up of one or more ordering specifications, separated by commas, each of which consists of an expression and an ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required