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 using the aggregation 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.

The only way to sort data in an order other than document order is 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 of 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, you have to use a FLWOR.

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 optional modifier. The expression can only return one value for each item being sorted. In Example 7-1, there is only ...

Get XQuery now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.