SortExpr

Sort a sequence of items.

Top of page

Related Syntax Constructs

The following construct(s) refer to this construct:


Syntax

SortExpr

graphics/SortExpr.png

Expr SortSpecList

Description

A SortExpr sorts a sequence of items that is specified as the expression to the left of the keywords sort by according to an ordering expression, the SortSpecList. The result of evaluating the expression that precedes the keywords sort by is the input sequence. The sort result is the output sequence.

The items of the input sequence are reordered according to the ordering expressions in the SortSpecList. If there is more than one ordering expression, then the first one is the primary sort criterion and the other expressions are then processed from left to right. For each ordering expression you can specify a sort direction, either ascending or descending, with ascending as default.

For the sort operation to succeed, a common supertype of each ordering expression is determined which is used for sorting. Each expression must return not more than one item per object to be sorted. Also the comparison operator gt must be defined for this type, otherwise an error is raised.

Using the keyword stable does not have any effect and so the keyword can be left out.

Example

  • Sort all books that cost less than 50 dollars by first author and title:

    declare namespace xs="http://www.w3.org/2001/XMLSchema"
    for $a in input()/bib/book
    where xs:decimal($a/price) < 50
    return $a
    sort by (author[1]/last, title)

    The input sequence comprises all book elements that cost less than 50 dollars. The primary sort criterion is author[1]/last, so the input sequence is ordered by the last child element of the first author element. Within each author group, the input sequence is ordered by the title element.