Evaluation Order and Parentheses

A query can contain many nested expressions that are not necessarily delimited by parentheses. Therefore, it is important to understand which expressions are evaluated first. In most cases, the evaluation order (also known as the precedence) of expressions is straightforward. For example, in the expression:

if ($x < 12 and $y > 0)
then $x + $y else $x - $y

it is easy to see that the if, then, and else keywords are all parts of the same expression that should be evaluated as a whole after all the sub-expressions have been evaluated. In the cases where it is not obvious, this book explains the evaluation order of that type of expression. For example, any and operators are evaluated before or operators, so that:

true() and true() or false() and false( )

is the same as:

(true() and true( )) or (false() and false( ))

If there is doubt in your mind regarding which expression is evaluated first, it is likely that others reading your query will be uncertain too. In this case, it is best to surround the expressions in question with parentheses. For example, you can change the previous if-then-else expression to:

if (($x < 12) and ($y > 0)) then ($x + $y) else ($x - $y)

The meaning is exactly the same, but the evaluation order is clearer. Parentheses can also be used to change the evaluation order. For example, if you change the true/false example to:

true( ) and (true() or false( )) and false( )

it now has a different value (false) because the or expression ...

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.