Conditional (if-then-else) Expressions

XQuery allows conditional expressions using the keywords if, then, and else. The syntax of a conditional expression is shown in Figure 3-1.

Syntax of a conditional expression

Figure 3-1. Syntax of a conditional expression

The expression after the if keyword is known as the test expression. It must be enclosed in parentheses. If the test expression evaluates to true, the value of the entire conditional expression is the value of the then expression. Otherwise, it is the value of the else expression.

Example 3-1 shows a conditional expression (embedded in a FLWOR).

Example 3-1. Conditional expression

Query
for $prod in (doc("catalog.xml")/catalog/product)
return if ($prod/@dept = 'ACC')
       then <accessoryNum>{data($prod/number)}</accessoryNum>
       else <otherNum>{data($prod/number)}</otherNum>
Results
<otherNum>557</otherNum>
<accessoryNum>563</accessoryNum>
<accessoryNum>443</accessoryNum>
<otherNum>784</otherNum>

If the then expression and else expression are single expressions, they are not required to be in parentheses. However, to return the results of multiple expressions, they need to be concatenated together using a sequence constructor. For example, if in Example 3-1 you wanted to return an accessoryName element in addition to accessoryNum, you would be required to separate the two elements by commas and surround them with parentheses, effectively constructing a sequence of two ...

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.