XQuery Reference

Conditionals & Types

XQuery inherits XPath's if/then/else and its type system, then adds typeswitch — a branch on what a value *is* rather than on a boolean test. Together with instance of, cast as and treat as, these are the tools for writing a query that survives contact with messy, irregular documents rather than assuming every node looks the same.

if (…) then … else …

Conditional expression — else is mandatory

Shared with XPath 3.1, but far more common in XQuery because it usually sits inside a return clause to shape each row differently. The else branch is required; use else () when you want to emit nothing.

Example: if ($b/@stock > 0) then 'in stock' else 'sold out'

typeswitch (…) case … default …

Branch on the type of a value

Evaluates the operand once and takes the first case whose type matches. A default branch is mandatory. Bind the matched value with 'case $x as element() return …' when the branch needs it. This is the standard shape for a recursive document transformation.

Example: typeswitch ($n) case element(title) return 'title' default return 'other'

instance of

Test whether a value matches a type

Returns a boolean rather than branching. Useful in a where clause or a predicate when you only need a yes/no answer — for example filtering a mixed sequence down to just the attribute nodes.

Example: $n instance of element()

cast as

Convert a single atomic value to another type

Casting converts, and fails loudly if the value cannot be converted. Use castable as first when the input might be dirty, or the two-argument number()/xs:decimal() style when you would rather get NaN than an error.

Example: $b/price cast as xs:decimal

treat as

Assert a type without converting

Changes nothing at runtime except the static type the engine assumes — and raises an error if the assertion is wrong. It is an assertion for the optimizer and for your own sanity, not a conversion.

Example: $n treat as element()

some / every … satisfies

Quantified expression over a sequence

Shared with XPath, but worth knowing here: some returns true if at least one item satisfies the test, every if all do. Note that every over an empty sequence is true — a classic source of surprises in validation queries.

Example: every $p in //price satisfies $p > 0

← Back to the XQuery reference