ZorbaSource on GitHub
On this page

The big picture

  1. The idea in one paragraph
  2. Everything is a sequence
  3. Four kinds of items
  4. Nodes and values
  5. Null and the empty sequence
  6. Expressions, not statements
  7. XPath inside XQuery
  8. Coming from SQL
  9. XQuery and XSLT
  10. The specification family
  11. What Zorba supports

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:

One sequence, six items. Sequences hold any mix of item kinds. 42 "text" <book> @id <title> text { "k": 1 } [ 1, 2 ] upper-case#1 atomic value atomic value node (a tree) JSON object JSON array function item XQuery data model (XDM) added by JSONiq XQuery 3.0
XQuerymodel/flat.xq
(: Sequences never nest: inner parentheses just concatenate. :)
let $s := (1, (2, 3), (), ("four", (5)))
return (count($s), $s)
Resultzorba -i -r -f -q flat.xq
5 1 2 3 four 5

Why it matters: the first number is the count. Flattening is why you can concatenate results with a comma without worrying about levels of nesting.

XQuerymodel/singleton.xq
(: A single item and a one-item sequence are the same thing. :)
(
  deep-equal(42, (42)),
  count(42),
  (42)[1] + 0,
  count(()),
  empty(())
)
Resultzorba -i -r -f -q singleton.xq
true 1 42 0 true

Why 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:QName and 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 makes for-each, filter and fold-left possible.
XQuerymodel/kinds.xq
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, "&#10;")
Resultzorba -i -r -f -q kinds.xq
xs: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 item

Why 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).

XQuerymodel/atomize.xq
(: 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)
)
Resultzorba -i -r -f -q atomize.xq
true true 25 USD false true

Why 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:

JSONiqmodel/null-vs-empty.jq
(: 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)
]
Resultzorba -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:

XQuerymodel/xpath.xq
doc("../data/books.xml")//book[@lang = "es"]/title
Resultzorba -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.

SQLXQuery / JSONiqNote
FROM tfor $r in $rowsIterates any sequence: nodes, objects, numbers.
WHEREwhere, or a predicate [...]
JOIN ... ONtwo for clauses and a whereOuter joins use allowing empty.
GROUP BYgroup byAfter grouping, the other variables hold the whole group as a sequence.
ORDER BYorder by
ROW_NUMBER()count $n, at $pos
window functionstumbling window, sliding windowSplits a sequence into windows by start and end conditions.
SELECT listreturnBuilds any result: XML, JSON, text, nested structures.
NULL(), or null in JSONiqSee null and the empty sequence.
views, stored functionsfunctions and library modules
INSERT, UPDATE, DELETEUpdate Facility, JSONiq updates
tables, indexes, constraintsZorba collections, indexes, integrity constraintsZorba'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.

Core language, by version Extensions to XQuery 3.0 JSON JSONiq 1.0 Zorba and beyond XPath 1.0 1999, superseded by 2.0 XQuery 1.0, XPath 2.0 2007 XQuery 3.0, XPath 3.0 2014, the version Zorba targets XQuery 3.1 2017: maps, arrays, =>, ? Shared foundation data model (XDM), functions and operators, serialization, XML Schema types and validation Update Facility 1.0 2011: insert, delete, replace, rename, copy-modify Full Text 1.0 2011: contains text, stemming, wildcards; most features Scripting based on a W3C draft: assignment, while, blocks XQueryX queries written as XML; optional build flag JSONiq syntax .jq files: $o.key, $a[[1]], $a[], $$, null, true JSON in XQuery .xq files: $o("key"), $a(1), $a() JSONiq updates insert json, delete json, replace, rename, append XQDDF collections, indexes, integrity constraints Built-in modules files, HTTP, strings, math, JSON-XML, CSV XSLT shares XPath; not run
Implemented by Zorba Implemented, JSON-related Not implemented

What Zorba supports

Checked against the parser, the function library and the test suite in this repository.

SpecificationStatusDetails
XQuery 1.0 and 3.0YesVersion 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.0YesIncluding for-each, filter, fold-left, format-number, format-date, analyze-string, parse-xml, serialize, unparsed-text, and the math: functions.
XQuery 3.1NoA 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.1Yesimport schema, validate, typed data. Needs the Xerces-C build (the default full-release preset and the container image).
Update Facility 1.0YesInsert, delete, replace, rename, copy-modify-return, updating functions.
Full Text 1.0Mostlycontains 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.
ScriptingYesZorba'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.0YesBoth 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.
XQDDFYesZorba'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.0MostlyMethods xml, xhtml, html, text, json and json-xml-hybrid (the default). Character maps are not implemented.
XQueryXOptionalEnabled with the CMake option ZORBA_XQUERYX and libxslt. It is off by default and in the container image.
XSLTNoNot 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:

XQuerymodel/no-31.xq
(: 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>
Resultzorba -i -r -f -q no-31.xq
<compile query="xquery version &quot;3.0&quot;; 1 + 1">compiles</compile>
<compile query="xquery version &quot;3.1&quot;; 1 + 1">error XQST0031</compile>
<compile query="map { &quot;a&quot;: 1 }">error XPST0003</compile>
<compile query="(1, 2, 3) =&gt; count()">error XPST0003</compile>
<compile query="{ &quot;a&quot;: 1 }(&quot;a&quot;)">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.