# XQuery

From a path expression to grouping, windows, updates and text search. Each section is short: an idea, an example run by Zorba, its output, and why it is worth knowing.

## The sample data

Most examples read the same small file. `doc()` loads and parses an XML document; relative paths resolve against the location of the query file.

**XML**: `data/books.xml`

```xml
<library>
  <book id="b1" year="1967" lang="es">
    <title>Cien años de soledad</title>
    <author>Gabriel García Márquez</author>
    <price>18.50</price>
    <tags><tag>novel</tag><tag>magic realism</tag></tags>
  </book>
  <book id="b2" year="1979" lang="en">
    <title>Gödel, Escher, Bach</title>
    <author>Douglas Hofstadter</author>
    <price>24.00</price>
    <tags><tag>essay</tag><tag>mathematics</tag></tags>
  </book>
  <book id="b3" year="1984" lang="en">
    <title>Neuromancer</title>
    <author>William Gibson</author>
    <price>12.99</price>
    <tags><tag>novel</tag><tag>science fiction</tag></tags>
  </book>
  <book id="b4" year="1985" lang="es">
    <title>El amor en los tiempos del cólera</title>
    <author>Gabriel García Márquez</author>
    <price>16.00</price>
    <tags><tag>novel</tag></tags>
  </book>
</library>
```

## Paths

A path is a series of steps separated by `/`. Each step selects nodes relative to the nodes selected by the previous step. `//` means "at any depth". The result comes back in document order, without duplicates.

**XQuery**: `xquery/path-steps.xq`

```xquery
doc("../data/books.xml")/library/book/title
```

**Result**: `zorba -i -r -f -q path-steps.xq`

```
<title>Cien años de soledad</title>
<title>Gödel, Escher, Bach</title>
<title>Neuromancer</title>
<title>El amor en los tiempos del cólera</title>
```

**Why it matters:** a path returns nodes, not strings. The titles above are still elements that you can navigate further or copy into new documents.

## Predicates

Square brackets filter. A boolean predicate keeps the items for which it is true; a number selects by position, starting at 1. Predicates can be chained and can contain paths of their own.

**XQuery**: `xquery/path-predicates.xq`

```xquery
let $lib := doc("../data/books.xml")
return (
  <cheap-english>{ $lib//book[price < 20][@lang = "en"]/title/string() }</cheap-english>,
  <second-id>{ $lib//book[2]/@id/string() }</second-id>,
  <last-title>{ ($lib//book)[last()]/title/string() }</last-title>,
  <essayist>{ $lib//book[tags/tag = "essay"]/author/string() }</essayist>
)
```

**Result**: `zorba -i -r -f -q path-predicates.xq`

```
<cheap-english>Neuromancer</cheap-english>
<second-id>b2</second-id>
<last-title>El amor en los tiempos del cólera</last-title>
<essayist>Douglas Hofstadter</essayist>
```

**Why it matters:** `//book[2]` means "each book that is the second book child of its parent", while `(//book)[last()]` takes the last item of the whole sequence. The parentheses change the meaning.

## Axes

A step moves along an axis. `child::` is the default and `@` abbreviates `attribute::`. Others go up (`parent::`, written `..`, and `ancestor::`), sideways (`following-sibling::`, `preceding-sibling::`) or down (`descendant::`).

**XQuery**: `xquery/path-axes.xq`

```xquery
let $lib := doc("../data/books.xml")
return (
  <ancestor>{ $lib//tag[. = "science fiction"]/ancestor::book/@id/string() }</ancestor>,
  <following-sibling>{ $lib//title[. = "Neuromancer"]/following-sibling::author/string() }</following-sibling>,
  <preceding-sibling>{ $lib//book[@id = "b3"]/preceding-sibling::book/@id/string() }</preceding-sibling>,
  <descendants>{ count($lib//book[1]/descendant::*) }</descendants>,
  <parent>{ $lib//price[. > 20]/../@year/string() }</parent>
)
```

**Result**: `zorba -i -r -f -q path-axes.xq`

```
<ancestor>b3</ancestor>
<following-sibling>William Gibson</following-sibling>
<preceding-sibling>b1 b2</preceding-sibling>
<descendants>6</descendants>
<parent>1979</parent>
```

**Why it matters:** you can start from the node you found and move in any direction, instead of restructuring the query to come from the top.

## From nodes to values

Aggregates and string functions atomize their input. A function call can be a path step (`price/xs:decimal(.)`), and the simple map operator `!` applies an expression to each item of a sequence, with `.` bound to the item.

**XQuery**: `xquery/path-values.xq`

```xquery
let $books := doc("../data/books.xml")//book
return (
  <total>{ sum($books/price/xs:decimal(.)) }</total>,
  <latest>{ max($books/@year/xs:integer(.)) }</latest>,
  <authors>{ string-join(distinct-values($books/author), "; ") }</authors>,
  <shouting>{ string-join($books/title ! upper-case(.), " | ") }</shouting>
)
```

**Result**: `zorba -i -r -f -q path-values.xq`

```
<total>71.49</total>
<latest>1985</latest>
<authors>Gabriel García Márquez; Douglas Hofstadter; William Gibson</authors>
<shouting>CIEN AÑOS DE SOLEDAD | GÖDEL, ESCHER, BACH | NEUROMANCER | EL AMOR EN LOS TIEMPOS DEL CÓLERA</shouting>
```

**Why it matters:** converting with `xs:decimal` gives exact decimal arithmetic. Summing the untyped values directly would convert them to `xs:double`, with binary rounding.

## Comparisons and quantifiers

There are two families of comparison. **General comparisons** (`=`, `!=`, `<`, `>`, ...) compare sequences and are true if *any* pair of items matches. **Value comparisons** (`eq`, `ne`, `lt`, `gt`, ...) compare exactly one item with one item and raise an error otherwise. `some` and `every` quantify explicitly.

**XQuery**: `xquery/quantified.xq`

```xquery
let $books := doc("../data/books.xml")//book
return (
  <all-priced>{ every $b in $books satisfies $b/price > 0 }</all-priced>,
  <any-under-13>{ some $b in $books satisfies $b/price < 13 }</any-under-13>,
  <general>{ $books/@lang = "en" }</general>,
  <value>{ try { $books/@lang eq "en" } catch * { "eq needs exactly one item" } }</value>
)
```

**Result**: `zorba -i -r -f -q quantified.xq`

```
<all-priced>true</all-priced>
<any-under-13>true</any-under-13>
<general>true</general>
<value>eq needs exactly one item</value>
```

**Why it matters:** `$books/@lang = "en"` reads like an equality test but means "at least one book is in English". Use `eq` when you expect a single value and want to be told if you get several.

## FLWOR

The FLWOR expression (pronounced "flower") is the workhorse. `for` iterates, `let` binds a value, `where` filters, `order by` sorts and `return` builds the result for each surviving binding.

**XQuery**: `xquery/flwor-basic.xq`

```xquery
for $b in doc("../data/books.xml")//book
let $price := xs:decimal($b/price)
where $price < 20
order by $price descending
return <cheap price="{$price}">{ $b/title/string() }</cheap>
```

**Result**: `zorba -i -r -f -q flwor-basic.xq`

```
<cheap price="18.5">Cien años de soledad</cheap>
<cheap price="16">El amor en los tiempos del cólera</cheap>
<cheap price="12.99">Neuromancer</cheap>
```

**Why it matters:** the clauses can repeat and appear in almost any order, so a FLWOR covers what SQL spreads across SELECT, FROM, WHERE, ORDER BY and subqueries.

## Grouping

`group by` (XQuery 3.0) partitions the bindings by a key. After the clause, every other variable holds the sequence of values from its group, so `count($b)` counts the books of each author and `sum($price)` adds their prices.

**XQuery**: `xquery/flwor-group.xq`

```xquery
for $b in doc("../data/books.xml")//book
let $price := xs:decimal($b/price)
group by $author := string($b/author)
order by count($b) descending, $author
return <author name="{$author}" books="{count($b)}" total="{sum($price)}"/>
```

**Result**: `zorba -i -r -f -q flwor-group.xq`

```
<author name="Gabriel García Márquez" books="2" total="34.5"/>
<author name="Douglas Hofstadter" books="1" total="24"/>
<author name="William Gibson" books="1" total="12.99"/>
```

**Why it matters:** before 3.0 this needed `distinct-values` plus a nested query per key. Now it is a single clause.

## Positions and ranks

`for $x at $pos` binds the position of each item in the input sequence. The `count` clause numbers the bindings at the point where it appears, so after `order by` it gives a rank.

**XQuery**: `xquery/flwor-count.xq`

```xquery
for $b at $pos in doc("../data/books.xml")//book
order by xs:integer($b/@year) descending
count $rank
return <book rank="{$rank}" position="{$pos}" year="{$b/@year}">{ string($b/title) }</book>
```

**Result**: `zorba -i -r -f -q flwor-count.xq`

```
<book rank="1" position="4" year="1985">El amor en los tiempos del cólera</book>
<book rank="2" position="3" year="1984">Neuromancer</book>
<book rank="3" position="2" year="1979">Gödel, Escher, Bach</book>
<book rank="4" position="1" year="1967">Cien años de soledad</book>
```

**Why it matters:** the two numbers answer different questions: where the item was in the input, and where it is in the result.

## Joins

Two `for` clauses form a join; the predicate or `where` is the join condition. `allowing empty` keeps an outer binding even when the inner sequence is empty, like a left outer join.

**XQuery**: `xquery/flwor-join.xq`

```xquery
let $people := (<person name="William Gibson" born="1948"/>,
                <person name="Ursula K. Le Guin" born="1929"/>)
for $p in $people
for $b allowing empty in doc("../data/books.xml")//book[author = $p/@name]
return <row author="{$p/@name}" title="{$b/title}"/>
```

**Result**: `zorba -i -r -f -q flwor-join.xq`

```
<row author="William Gibson" title="Neuromancer"/>
<row author="Ursula K. Le Guin" title=""/>
```

**Why it matters:** joins work across documents and sources, not only across tables of one database.

## Windows

A window clause slides over a sequence and binds a whole sub-sequence at a time. A **tumbling** window starts a new window after the previous one ends; a **sliding** window starts one at every position that meets the start condition. `only end` drops windows whose end condition never became true.

**XQuery**: `xquery/flwor-tumbling.xq`

```xquery
for tumbling window $w in 1 to 10
    start at $s when true()
    end at $e when $e - $s eq 2
return <batch>{ $w }</batch>
```

**Result**: `zorba -i -r -f -q flwor-tumbling.xq`

```
<batch>1 2 3</batch>
<batch>4 5 6</batch>
<batch>7 8 9</batch>
<batch>10</batch>
```

**XQuery**: `xquery/flwor-sliding.xq`

```xquery
let $temps := (21, 23, 22, 26, 28, 27)
for sliding window $w in $temps
    start at $s when true()
    only end at $e when $e - $s eq 2
return round-half-to-even(avg($w), 1)
```

**Result**: `zorba -i -r -f -q flwor-sliding.xq`

```
22 23.7 25.3 27
```

**Why it matters:** batching, sessions in logs and moving averages over time series become declarative.

## Constructors

Direct constructors write XML literally. Curly braces inside content or attribute values evaluate an expression and insert its result.

**XQuery**: `xquery/ctor-direct.xq`

```xquery
let $books := doc("../data/books.xml")//book
return
  <ul class="books" count="{count($books)}">{
    for $b in $books
    return <li lang="{$b/@lang}" year="{$b/@year}">{ string($b/title) }</li>
  }</ul>
```

**Result**: `zorba -i -r -f -q ctor-direct.xq`

```
<ul class="books" count="4">
  <li lang="es" year="1967">Cien años de soledad</li>
  <li lang="en" year="1979">Gödel, Escher, Bach</li>
  <li lang="en" year="1984">Neuromancer</li>
  <li lang="es" year="1985">El amor en los tiempos del cólera</li>
</ul>
```

Computed constructors build nodes whose names are themselves computed.

**XQuery**: `xquery/ctor-computed.xq`

```xquery
let $level := 2
let $name := "release-notes"
return element { concat("h", $level) } {
  attribute id { $name },
  attribute class { "title" },
  text { "Release notes" }
}
```

**Result**: `zorba -i -r -f -q ctor-computed.xq`

```
<h2 id="release-notes" class="title">Release notes</h2>
```

**Why it matters:** output is built as a tree, so it is always well formed, and characters such as `<` and `&` are escaped by the serializer.

## Functions

Functions are declared in the prolog, before the query body. Functions in a main module go in the `local` namespace. Parameter and return types are optional; when present, arguments are checked and converted.

**XQuery**: `xquery/func-declare.xq`

```xquery
declare function local:discount($price as xs:decimal, $pct as xs:integer)
  as xs:decimal
{
  $price - $price * $pct div 100
};

declare function local:fib($n as xs:integer) as xs:integer
{
  if ($n lt 2) then $n else local:fib($n - 1) + local:fib($n - 2)
};

(
  local:discount(24.00, 25),
  for $i in 0 to 10 return local:fib($i)
)
```

**Result**: `zorba -i -r -f -q func-declare.xq`

```
18 0 1 1 2 3 5 8 13 21 34 55
```

**Why it matters:** recursion is the natural way to walk trees of unknown depth, and typed signatures catch mistakes early.

## Functions as values

XQuery 3.0 has function items: inline functions (`function($x) { ... }`), named references (`upper-case#1`, where the number is the arity) and dynamic calls (`$f(3)`). The standard library has the usual higher-order functions.

**XQuery**: `xquery/func-higher-order.xq`

```xquery
let $square := function($x) { $x * $x }
let $even := function($x) { $x mod 2 eq 0 }
let $nums := 1 to 6
return (
  for-each($nums, $square),
  filter($nums, $even),
  fold-left($nums, 0, function($acc, $x) { $acc + $x }),
  for-each(("a", "b"), upper-case#1),
  $square($square(3))
)
```

**Result**: `zorba -i -r -f -q func-higher-order.xq`

```
1 4 9 16 25 36 2 4 6 21 A B 81
```

**Why it matters:** behaviour can be passed as a parameter, which makes generic library functions possible.

## Modules

A library module declares a target namespace and contains functions and variables in it. A main module imports it with `import module namespace`; the `at` clause gives its location.

**XQuery module**: `xquery/lib/geo.xqm`

```xqm
module namespace geo = "http://example.org/geo";

declare namespace math = "http://www.w3.org/2005/xpath-functions/math";

declare variable $geo:earth-radius-km := 6371;

declare function geo:deg-to-rad($d as xs:double) as xs:double
{
  $d * math:pi() div 180
};

(: Great-circle distance in km between two (lat, lon) points. :)
declare function geo:distance($lat1 as xs:double, $lon1 as xs:double,
                              $lat2 as xs:double, $lon2 as xs:double)
  as xs:double
{
  let $dlat := geo:deg-to-rad($lat2 - $lat1)
  let $dlon := geo:deg-to-rad($lon2 - $lon1)
  let $a := math:pow(math:sin($dlat div 2), 2)
            + math:cos(geo:deg-to-rad($lat1)) * math:cos(geo:deg-to-rad($lat2))
              * math:pow(math:sin($dlon div 2), 2)
  return 2 * $geo:earth-radius-km * math:asin(math:sqrt($a))
};
```

**XQuery**: `xquery/func-module.xq`

```xquery
import module namespace geo = "http://example.org/geo" at "lib/geo.xqm";

(: Mexico City to Guadalajara, rounded to whole kilometres :)
round(geo:distance(19.4326, -99.1332, 20.6597, -103.3496))
```

**Result**: `zorba -i -r -f -q func-module.xq`

```
461
```

**Why it matters:** modules are how code is shared, and how Zorba's built-in libraries are exposed (see [built-in modules](zorba.md#modules)).

## Strings, numbers, dates

The standard function library includes regular expressions (`matches`, `replace`, `tokenize`, `analyze-string`) and, since 3.0, formatting of numbers and dates. The `||` operator concatenates strings.

**XQuery**: `xquery/strings.xq`

```xquery
(
  <tokens>{ tokenize("a, b,c", ",\s*") }</tokens>,
  <reordered>{ replace("2026-10-29", "(\d+)-(\d+)-(\d+)", "$3/$2/$1") }</reordered>,
  <matches>{ matches("Neuromancer", "^neuro", "i") }</matches>,
  <number>{ format-number(1234567.891, "#,##0.00") }</number>,
  <date>{ format-date(xs:date("2026-10-29"), "[D1] [MNn] [Y]") }</date>
)
```

**Result**: `zorba -i -r -f -q strings.xq`

```
<tokens>a b c</tokens>
<reordered>29/10/2026</reordered>
<matches>true</matches>
<number>1,234,567.89</number>
<date>29 October 2026</date>
```

**Why it matters:** most text munging needs no extension library.

## Types and casting

Every atomic value has a type. Constructor functions like `xs:date("...")` and `cast as` convert; `castable as` tests without failing; `instance of` checks the type of a value. Integer division with `div` gives an exact decimal; with doubles you get binary floating point.

**XQuery**: `xquery/types-cast.xq`

```xquery
(
  xs:integer("42") + 1,
  "4x2" castable as xs:integer,
  "2026-10-29" cast as xs:date,
  xs:date("2026-10-29") + xs:dayTimeDuration("P3D"),
  xs:date("2026-12-25") - xs:date("2026-10-29"),
  3 instance of xs:decimal,
  3.0 instance of xs:integer,
  1 div 3,
  1e0 div 3
)
```

**Result**: `zorba -i -r -f -q types-cast.xq`

```
43 false 2026-10-29 2026-11-01 P57D true false 0.333333333333333333 0.3333333333333333
```

`switch` selects by value, `typeswitch` by type (see [the item kinds example](map.md#items)).

**XQuery**: `xquery/types-switch.xq`

```xquery
for $code in ("es", "en", "fr")
return switch ($code)
  case "es" return "Spanish"
  case "en" return "English"
  default return concat("unknown: ", $code)
```

**Result**: `zorba -i -r -f -q types-switch.xq`

```
Spanish English unknown: fr
```

**Why it matters:** dates, durations and decimals behave like values with arithmetic, not like strings you have to parse again.

## Schema validation

With an XML Schema imported, `validate` checks a node and annotates it with types. Atomizing a validated element then gives typed values: here `xs:positiveInteger` and `xs:decimal` instead of untyped text. Invalid input raises `err:XQDY0027`.

**.xsd**: `xquery/lib/order.xsd`

```xsd
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
           targetNamespace="http://example.org/order"
           elementFormDefault="qualified">
  <xs:element name="order">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="qty" type="xs:positiveInteger"/>
        <xs:element name="price" type="xs:decimal"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>
```

**XQuery**: `xquery/validate.xq`

```xquery
import schema namespace o = "http://example.org/order" at "lib/order.xsd";
declare namespace err = "http://www.w3.org/2005/xqt-errors";

let $order := validate { <o:order><o:qty>3</o:qty><o:price>2.50</o:price></o:order> }
return (
  <total>{ $order/o:qty * $order/o:price }</total>,
  <typed>{ data($order/o:qty) instance of xs:positiveInteger }</typed>,
  <invalid>{
    try { validate { <o:order><o:qty>-1</o:qty><o:price>2.50</o:price></o:order> } }
    catch err:XQDY0027 { "rejected" }
  }</invalid>
)
```

**Result**: `zorba -i -r -f -q validate.xq`

```
<total>7.5</total>
<typed>true</typed>
<invalid>rejected</invalid>
```

**Why it matters:** input checking and typing come from the schema you already have, not from hand-written checks in every query.

## Errors

Errors are identified by QNames. `try`/`catch` (XQuery 3.0) catches them by name, by namespace wildcard or with `*`; inside the `catch`, variables such as `$err:code` and `$err:description` describe the error. `error()` raises your own.

**XQuery**: `xquery/errors-try.xq`

```xquery
declare namespace err = "http://www.w3.org/2005/xqt-errors";
declare namespace app = "http://example.org/app";

(
  <cast>{
    try { xs:integer("abc") }
    catch err:FORG0001 { "not a number: " || $err:code }
  }</cast>,
  <division>{
    try { 1 div 0 }
    catch * { "caught " || local-name-from-QName($err:code) }
  }</division>,
  <custom>{
    try { error(QName("http://example.org/app", "app:E42"), "stock is negative") }
    catch app:E42 { $err:description }
  }</custom>
)
```

**Result**: `zorba -i -r -f -q errors-try.xq`

```
<cast>not a number: err:FORG0001</cast>
<division>caught FOAR0001</division>
<custom>stock is negative</custom>
```

XQuery 3.0 says the `err` prefix is predeclared. In Zorba some catch clauses fail with `XPST0081` ("can not expand prefix") unless the prefix is declared, so the examples on this site declare it explicitly. The declaration is valid in any processor.

**Why it matters:** failures in one part of a result, such as a malformed date in one record, can be handled without aborting the whole query.

## Updates

The Update Facility adds expressions that change nodes: `insert node`, `delete node`, `replace node`, `replace value of node` and `rename node`. Changes are collected into a pending update list and applied together at the end, so expressions never see a half-updated tree. `copy`/`modify`/`return` applies updates to a copy and returns it.

**XQuery**: `xquery/update-transform.xq`

```xquery
let $book := doc("../data/books.xml")//book[@id = "b3"]
return
  copy $b := $book
  modify (
    replace value of node $b/price with "9.99",
    insert node <tag>cyberpunk</tag> into $b/tags,
    delete node $b/@lang,
    rename node $b/author as "writer"
  )
  return $b
```

**Result**: `zorba -i -r -f -q update-transform.xq`

```
<book id="b3" year="1984">
  <title>Neuromancer</title>
  <writer>William Gibson</writer>
  <price>9.99</price>
  <tags>
    <tag>novel</tag>
    <tag>science fiction</tag>
    <tag>cyberpunk</tag>
  </tags>
</book>
```

**XQuery**: `xquery/update-original.xq`

```xquery
(: copy/modify works on a copy: the original stays untouched. :)
let $book := doc("../data/books.xml")//book[@id = "b3"]
let $changed :=
  copy $b := $book
  modify replace value of node $b/price with "9.99"
  return $b
return (string($changed/price), string($book/price))
```

**Result**: `zorba -i -r -f -q update-original.xq`

```
9.99 12.99
```

**Why it matters:** "the same document with a few changes" is one expression instead of a full rebuild. To make changes persist across statements, apply them to nodes in a [collection](zorba.md#collections) or use [scripting](zorba.md#scripting).

## Full-text search

`contains text` searches the words of a node, not its characters: it tokenizes the text, ignores case by default and can apply stemming, wildcards, stop words and thesauri.

**XQuery**: `xquery/fulltext-basic.xq`

```xquery
let $docs := (
  <p id="1">The quick brown fox jumps over the lazy dog.</p>,
  <p id="2">Foxes were running through the fields.</p>,
  <p id="3">A slow brown bear sleeps all winter.</p>)
return (
  <plain>{ $docs[. contains text "fox"]/@id/string() }</plain>,
  <stemmed>{ $docs[. contains text "fox" using stemming]/@id/string() }</stemmed>,
  <any-word>{ $docs[. contains text "bear fox" any word]/@id/string() }</any-word>
)
```

**Result**: `zorba -i -r -f -q fulltext-basic.xq`

```
<plain>1</plain>
<stemmed>1 2</stemmed>
<any-word>1 3</any-word>
```

Searches combine with `ftand`, `ftor` and `ftnot`, and can be restricted by distance or window.

**XQuery**: `xquery/fulltext-ops.xq`

```xquery
let $docs := (
  <p id="1">The quick brown fox jumps over the lazy dog.</p>,
  <p id="2">Foxes were running through the fields.</p>,
  <p id="3">A slow brown bear sleeps all winter.</p>)
return (
  <and>{ $docs[. contains text "brown" ftand "dog"]/@id/string() }</and>,
  <not>{ $docs[. contains text "brown" ftand ftnot "bear"]/@id/string() }</not>,
  <window>{ $docs[. contains text "quick" ftand "fox" window 3 words]/@id/string() }</window>,
  <wildcard>{ $docs[. contains text "run.*" using wildcards]/@id/string() }</wildcard>
)
```

**Result**: `zorba -i -r -f -q fulltext-ops.xq`

```
<and>1</and>
<not>1</not>
<window>1</window>
<wildcard>2</wildcard>
```

**Why it matters:** "fox" does not match "Foxes" as a substring test would, but it does with stemming. Word-aware search is part of the query language instead of a separate engine.
