The big picture
XQuery and JSONiq are easy to underestimate. They look like path expressions with some loops, but they are complete functional languages over one data model, with optional layers for updates, text search, side effects and storage. This page lays out the whole map before the tutorials go into detail.
The idea in one paragraph
Every value is a sequence of items. An item is an atomic value (a number, a string, a date), a node of an XML tree, a JSON object or array, or a function. Every construct of the language is an expression that takes sequences and returns a sequence, so expressions nest freely: a path can appear inside a loop, a loop inside an element constructor, a constructor inside a function argument. XPath is the sublanguage for navigating trees; XQuery adds variables, loops, sorting, grouping, constructors, functions and modules; JSONiq adds JSON. Extensions add updates, full-text search, imperative scripting and persistent collections.
Everything is a sequence
A sequence is an ordered list of zero or more items. Three rules explain most of what surprises newcomers:
- Sequences are flat. A sequence never contains another sequence. Writing
(1, (2, 3))gives the three-item sequence(1, 2, 3). To nest, you need a structure: an XML element or a JSON array. - One item is a sequence of length one. There is no difference between
42and(42), so functions that "return a value" and functions that "return a list" are the same thing. - The empty sequence
()stands for "nothing". A path that matches nothing returns(), and most functions given()return()rather than failing.
(: Sequences never nest: inner parentheses just concatenate. :)
let $s := (1, (2, 3), (), ("four", (5)))
return (count($s), $s)zorba -i -r -f -q flat.xq5 1 2 3 four 5Why it matters: the first number is the count. Flattening is why you can concatenate results with a comma without worrying about levels of nesting.
(: A single item and a one-item sequence are the same thing. :)
(
deep-equal(42, (42)),
count(42),
(42)[1] + 0,
count(()),
empty(())
)zorba -i -r -f -q singleton.xqtrue 1 42 0 trueWhy it matters: there is no separate "scalar" and "list" world. Predicates like [1] work on any value, and count, empty and friends are the way to ask how many items you have.
Four kinds of items
- Atomic values
- Typed scalars. The types come from XML Schema:
xs:string,xs:integer,xs:decimal,xs:double,xs:boolean,xs:date,xs:dateTime,xs:duration,xs:QNameand a few dozen more. Decimal arithmetic is exact; dates and durations have real arithmetic. - Nodes
- The parts of an XML tree: document, element, attribute, text, comment, processing instruction and namespace nodes. A node has an identity and a position in its tree, so it has a parent, children and siblings.
- JSON items
- Objects (unordered string-keyed maps) and arrays (ordered lists whose members can be sequences of any length, flattened when you take them out). JSONiq adds them to the data model, together with the atomic value
null. - Function items
- Functions as values (XQuery 3.0): named function references like
upper-case#1, inline functions, and partial applications. They are what makesfor-each,filterandfold-leftpossible.
let $items := (42, "text", 2.5e0, xs:date("2026-10-29"),
<e/>, text { "t" }, { "k": 1 }, [ 1, 2 ], upper-case#1)
let $kinds :=
for $item in $items
return typeswitch ($item)
case xs:integer return "xs:integer atomic value"
case xs:string return "xs:string atomic value"
case xs:double return "xs:double atomic value"
case xs:date return "xs:date atomic value"
case element() return "element() node"
case text() return "text() node"
case object() return "object() JSON item"
case array() return "array() JSON item"
case function(*) return "function(*) function item"
default return "something else"
return string-join($kinds, " ")zorba -i -r -f -q kinds.xqxs:integer atomic value
xs:string atomic value
xs:double atomic value
xs:date atomic value
element() node
text() node
object() JSON item
array() JSON item
function(*) function itemWhy it matters: typeswitch and instance of work uniformly across every kind of item, which is how one query handles XML and JSON input with the same code.
Nodes and values
A node is not its text. When an operation needs a value (arithmetic, comparison, a function that takes a string), the node is atomized: its typed value is extracted. Without a schema, the typed value of an element is xs:untypedAtomic, which converts to whatever the context needs, so price * 2 just works. With a schema (see types), atomization yields properly typed values.
Nodes also have identity: two elements with the same content are equal by value (deep-equal) but are not the same node (is).
(: Nodes have identity and structure; atomization extracts their typed value. :)
let $p := <price currency="USD">12.50</price>
return (
$p instance of element(),
data($p) instance of xs:untypedAtomic,
data($p) * 2,
string($p/@currency),
<price>12.50</price> is $p,
deep-equal(<price currency="USD">12.50</price>, $p)
)zorba -i -r -f -q atomize.xqtrue true 25 USD false trueWhy it matters: most "why did my comparison fail" puzzles are about atomization or identity. Keep the two ideas apart and the language becomes predictable.
Null and the empty sequence
XQuery has no null. "No value" is the empty sequence, and it propagates: () + 1 is (). JSON needs a real null because {"coupon": null} and {} are different documents. JSONiq therefore has both, and they mean different things:
nullis an item. A sequence containing it has length one.- Looking up a key that does not exist returns
(), length zero.
(: null is an item; a missing key is the empty sequence. :)
let $o := { "a": null, "b": [] }
return [
count($o.a),
count($o.missing),
size($o.b),
$o.a instance of null,
empty($o.missing)
]zorba -i -r -f -q null-vs-empty.jq[ 1, 0, 0, true, true ]Why it matters: you can tell "explicitly null" from "absent" in a JSON document, which most JSON query tools blur. The JSONiq page shows how this plays out in queries.
Expressions, not statements
A query is one expression whose value is the result. There are no statements to sequence and no variables to reassign: let binds a name to a value once, if returns a value, and a for loop returns the concatenation of what each iteration returns. This is what lets a query nest a loop inside an element constructor inside a function call.
The absence of side effects is also what makes queries optimizable: Zorba can reorder, inline and rewrite expressions. Updates and scripting, described below, are carefully specified exceptions.
XPath inside XQuery
XPath is the expression language for addressing parts of a tree: //book[@lang = "es"]/title. XQuery 1.0 was defined as XPath 2.0 plus a prolog (declarations of namespaces, variables, functions and modules), FLWOR expressions, node constructors and a type system. XQuery 3.0 extends XPath 3.0 the same way. As a result, every XPath 2.0 or 3.0 expression is already a complete XQuery query:
doc("../data/books.xml")//book[@lang = "es"]/titlezorba -i -r -f -q xpath.xq<title>Cien años de soledad</title>
<title>El amor en los tiempos del cólera</title>Why it matters: if you have used XPath in a browser, in XSLT or in an XML library, you already know the navigation part of XQuery.
XPath 1.0, the version most libraries still ship, has no sequences (it has node-sets), only four data types and no conditional or loop expressions. XQuery is built on the 2.0 model and later.
Coming from SQL
The FLWOR expression (for, let, where, order by, return) plays the role of SELECT, but works on nested data and returns any shape you construct.
| SQL | XQuery / JSONiq | Note |
|---|---|---|
FROM t | for $r in $rows | Iterates any sequence: nodes, objects, numbers. |
WHERE | where, or a predicate [...] | |
JOIN ... ON | two for clauses and a where | Outer joins use allowing empty. |
GROUP BY | group by | After grouping, the other variables hold the whole group as a sequence. |
ORDER BY | order by | |
ROW_NUMBER() | count $n, at $pos | |
| window functions | tumbling window, sliding window | Splits a sequence into windows by start and end conditions. |
SELECT list | return | Builds any result: XML, JSON, text, nested structures. |
NULL | (), or null in JSONiq | See null and the empty sequence. |
| views, stored functions | functions and library modules | |
INSERT, UPDATE, DELETE | Update Facility, JSONiq updates | |
| tables, indexes, constraints | Zorba collections, indexes, integrity constraints | Zorba's data definition facility (XQDDF). |
The deeper difference is the data model: SQL rows are flat and typed by a fixed schema; XQuery items can be trees of any depth, and a schema is optional.
XQuery and XSLT
XSLT 2.0 and 3.0 share XPath, the data model and the function library with XQuery. They differ in style: XSLT is organized as template rules that fire on the nodes of the input (push processing), while XQuery is organized as expressions that pull the data they need. Document-to-document transformation with many small rules tends to read better in XSLT; querying, joining and building new structures tends to read better in XQuery. Zorba runs XQuery and JSONiq only; it does not execute XSLT stylesheets.
The specification family
XQuery is not one document but a family of W3C specifications plus JSONiq and Zorba's own extensions. The diagram shows how they relate and what Zorba implements; the table below it gives the details.
What Zorba supports
Checked against the parser, the function library and the test suite in this repository.
| Specification | Status | Details |
|---|---|---|
| XQuery 1.0 and 3.0 | Yes | Version declarations "1.0" and "3.0" are accepted; 3.0 is the default. Includes group by, windows, count, allowing empty, try/catch, switch, higher-order functions, ! and ||. Serialization options given as an XDM instance in output declarations are not supported. |
| XPath and XQuery Functions and Operators 3.0 | Yes | Including for-each, filter, fold-left, format-number, format-date, analyze-string, parse-xml, serialize, unparsed-text, and the math: functions. |
| XQuery 3.1 | No | A xquery version "3.1" declaration is rejected. There are no map { } or square-array constructors in the XQuery 3.1 sense, no => arrow operator, no ? lookup operator and no 3.1 functions such as fn:parse-json or fn:json-doc. JSON is handled by JSONiq instead. |
| XML Schema 1.0 and 1.1 | Yes | import schema, validate, typed data. Needs the Xerces-C build (the default full-release preset and the container image). |
| Update Facility 1.0 | Yes | Insert, delete, replace, rename, copy-modify-return, updating functions. |
| Full Text 1.0 | Mostly | contains text with stemming, wildcards, thesaurus, stop words, case and diacritics options, boolean operators, distance and window. The repository's known-issues file notes that it is not completely implemented. |
| Scripting | Yes | Zorba's own variant of the W3C Scripting Extension drafts, which never became a Recommendation: variable, assignment with :=, blocks, while, exit returning, sequential functions. break and continue do not work inside a FLWOR. |
| JSONiq 1.0 | Yes | Both syntaxes: the JSONiq syntax (.jq files or --jsoniq) and the JSONiq extension to XQuery (JSON constructors and navigation in .xq files). Includes JSONiq updates and the jn: and libjn: function libraries. |
| XQDDF | Yes | Zorba's data definition facility: static and dynamic collections, value and general indexes, integrity constraints. Indexes are used when probed explicitly; the optimizer does not rewrite queries to use them automatically. |
| Serialization 3.0 | Mostly | Methods xml, xhtml, html, text, json and json-xml-hybrid (the default). Character maps are not implemented. |
| XQueryX | Optional | Enabled with the CMake option ZORBA_XQUERYX and libxslt. It is off by default and in the container image. |
| XSLT | No | Not part of Zorba. |
The XQuery 3.1 rows are easy to check. This query compiles other queries at run time with the zorba-query module and reports the result:
(: Compile a few queries at run time and report what Zorba accepts. :)
import module namespace zq = "http://zorba.io/modules/zorba-query";
declare namespace an = "http://zorba.io/annotations";
declare namespace err = "http://www.w3.org/2005/xqt-errors";
declare %an:sequential function local:compile($query as xs:string) as xs:string
{
try {
{ variable $key := zq:prepare-main-module($query); "compiles" }
}
catch * { "error " || local-name-from-QName($err:code) }
};
for $query in ('xquery version "3.0"; 1 + 1',
'xquery version "3.1"; 1 + 1',
'map { "a": 1 }',
'(1, 2, 3) => count()',
'{ "a": 1 }("a")')
return <compile query="{$query}">{ local:compile($query) }</compile>zorba -i -r -f -q no-31.xq<compile query="xquery version "3.0"; 1 + 1">compiles</compile>
<compile query="xquery version "3.1"; 1 + 1">error XQST0031</compile>
<compile query="map { "a": 1 }">error XPST0003</compile>
<compile query="(1, 2, 3) => count()">error XPST0003</compile>
<compile query="{ "a": 1 }("a")">compiles</compile>Why it matters: XQuery 3.1 code written for other processors will not run unchanged. The last line shows the JSONiq way to do what 3.1 does with maps: a JSON object, looked up by calling it with a key.