XML Order By: Handling Collation and Missing Values

Sorting XML query results requires a clear understanding of how the order by clause processes linguistic rules and absent data. In standard XML query technologies such as XQuery and SQL/XML, the order by clause sorts extracted nodes and atomic values based on specified collation rules for text comparison and provides explicit keywords—such as empty greatest and empty least—to determine whether missing or empty values appear at the beginning or end of the result set.

Collation in XML Sorting

Collation dictates the rules for comparing and sorting character strings, accounting for cultural conventions, case sensitivity, and accents. When sorting string data within an XML query:

Handling Missing and Empty Values

In XML structures, an element or attribute may be absent entirely, or it may evaluate to an empty sequence (()). The order by clause handles these missing values using explicit position specifiers:

Example Syntax

A comprehensive XQuery order by clause combining collation, sort direction, and missing value management follows this structure:

for $employee in /company/employees/employee
order by $employee/department 
    collation "http://www.w3.org/2005/xpath-functions/collation/codepoint" 
    descending 
    empty least,
    $employee/lastName ascending
return $employee

In this example, employees without a department element will appear at the very end because the sort is descending and designated as empty least. Secondary sorting on lastName applies standard ascending order to resolve ties among identical departments.