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 ...

Get XQuery, 2nd Edition 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.