Comparing Numeric Values

Two numeric values can be compared using the general comparison operators: =, !=, <, <=, >, and >=. Values of different numeric types can be compared; one is promoted to the other's type. Nodes that contain numeric values can also be compared using these operators; in that case, they are atomized to extract their typed values. Table 16-2 shows some examples of comparing numeric values.

Some caution should be used when comparing untyped values using the general comparison operators. When an untyped value is compared to a numeric value (for example, a numeric literal), it is cast to the numeric type. However, when two untyped values are compared, they are treated like strings. This means that, for example, the untyped value 100 would evaluate to less than the value 99. If you want to compare two untyped values, you must explicitly cast the value(s) to a numeric type, as shown in the fourth example in Table 16-2.

Table 16-2. Comparing numeric values a

Example

Value

[a]

doc("prices.xml")//prod[3]/discount > 10

false

doc("prices.xml")//prod[3]/discount gt 10

Type error

doc("prices.xml")//prod[3]/discount > doc("prices.xml")//prod[1]/discount

true (it is comparing the string 3.99 to the string 10.00)

doc("prices.xml")//prod[3]/number(discount) >

doc("prices.xml")//prod[1]/number(discount)

false (it is comparing the number 3.99 to the number 10.00)

3 gt 2

true

1 = 1.0

true

xs:float("NaN") = xs:float("NaN")

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.