XQuery - Basics - FLWOR Expressions
Thursday 12th November 2026
Thursday 12th November 2026
Running XQuery with Elemental
FLWOR Statements
Grouping in XQuery
Windowing in XQuery
We will use Elemental
You have been provided with server access details!
From Elemental Dashboard in your Web Browser, open: eXide – XQuery IDE
Copy and Paste the Following XQuery:
<dates>
<today>{current-date()}</today>
<nice>{fn:format-date(current-date(), "[FNn], [D1o] [MNn] [Y]")}</nice>
</dates>
Run the query by pressing the “Eval” button
Q: What is the result?
Q: How is this different to XPath?
Q: Why is the function format-date prefixed with fn:?
Challenges for you to implement in XQuery:
What was the date one week ago?
What was the date one month ago?
What day was the 4th February 1981?
How many days old are you?
Use the function xs:dayTimeDuration() and its friends!
What was the date one week ago?
current-date() - xs:dayTimeDuration("P7D")
What was the date one month ago?
current-date() - xs:yearMonthDuration("P1M")
What day was the 4th February 1981?
fn:format-date(xs:date("1981-02-04"), "[FNn]")
How many days old are you? (Substitute your birthday)!
xs:date("1981-02-04") - current-date()
The primary construct in XQuery is the FLWOR ('flower') expression.
Historically, i.e. in XQuery 1.0, it consists of the following clauses:
XQuery 3.0 augments this with additional clauses:
The for clause iterates over an XPath sequence binding each item in turn to a variable.
An extended XPath ForClause that adds:
allowing empty
ForClause ::= "for" ForBinding ("," ForBinding)*
ForBinding ::= "$" VarName TypeDeclaration? AllowingEmpty? PositionalVar? "in" ExprSingle
TypeDeclaration ::= "as" SequenceType
AllowingEmpty ::= "allowing" "empty"
PositionalVar ::= "at" "$" VarName
When using XQuery with an XML database it is quite common to specify a collection
(using the fn:collection function) as the expression in a ForBinding!
Q: What do the following XQuery produce?
for $x at $y in ("a", "b", "c")
return
$y || ":" || $x
let $d := ("a", "b", "c")
for $x in $d, $y in $d
return
$x || ":" || $y
let $d := ("a", "b", "c")
for $x in $d
for $y in $d
return
concat($x, ":", $y)
for $x allowing empty at $y in ("a", "b", "c")[4]
return
$x || ":" || $y
("1:a", "2:b", "3:c")
("a:a", "a:b", "a:c", "b:a", "b:b", "b:c", "c:a", "c:b", "c:c")
("a:a", "a:b", "a:c", "b:a", "b:b", "b:c", "c:a", "c:b", "c:c")
":0"
The let clause binds the result of an expression to a variable.
An extended XPath LetClause that makes XQuery syntax more consistent.
LetClause ::= "let" LetBinding ("," LetBinding)*
LetBinding ::= "$" VarName TypeDeclaration? ":=" ExprSingle
TypeDeclaration ::= "as" SequenceType
Q: What do the following XQuery produce?
let $x := ("a", "b", "c"), $y := (1, 2, 3)
return
string-join($x, ",") || ":" || string-join($y, ",")
let $x := ("a", "b", "c"),
$y := (1, 2, 3)
return
$x => string-join(",") || ":" || $y => string-join(",")
let $x := ("a", "b", "c")
$y := (1, 2, 3)
return
string-join($x, ",") || ":" || string-join($y, ",")
let $x := ("a", "b", "c")
let $y := (1, 2, 3)
return
string-join((string-join($x, ","), string-join($y, ",")), ":")
let $x := ("a", "b", "c"),
let $y := (1, 2, 3)
return
string-join($x, ",") || ":" || string-join($y, ",")
a,b,c:1,2,3
a,b,c:1,2,3
Syntax error!
a,b,c:1,2,3
Syntax error!
The for (tumbling|sliding) window clause iterates over an XPath sequence binding, and generates a sequence of tuples
in the output tuple stream.
Imagine looking through a window where you can only see part of the landscape!
Always starts with for, but is quite different from a ForClause.
Has several control conditions: start, end.
Allows you to bind variables to the Window, Current Item, Previous Item, and Next Item.
WindowClause ::= "for" (TumblingWindowClause | SlidingWindowClause)
TumblingWindowClause ::= "tumbling" "window" "$" VarName TypeDeclaration? "in" ExprSingle WindowStartCondition WindowEndCondition?
SlidingWindowClause ::= "sliding" "window" "$" VarName TypeDeclaration? "in" ExprSingle WindowStartCondition WindowEndCondition
WindowStartCondition ::= "start" WindowVars "when" ExprSingle
WindowEndCondition ::= "only"? "end" WindowVars "when" ExprSingle
WindowVars ::= ("$" CurrentItem)? PositionalVar? ("previous" "$" PreviousItem)? ("next" "$" NextItem)?
CurrentItem ::= EQName
PositionalVar ::= "at" "$" VarName
PreviousItem ::= EQName
NextItem ::= EQName
Q: What do the following XQuery produce?
for tumbling window $w in ("a", "b", "c", 10, 20, 30)
start at $s when fn:true()
end at $e when $e - $s eq 1
return
<window>{$w}</window>
for tumbling window $w in (2, 4, 6, 8, 10, 12, 14)
start at $s when fn:true()
end at $e when $e - $s eq 2
return
avg($w)
for tumbling window $w in (2, 4, 6, 8, 10, 12, 14)
start at $s when fn:true()
only end at $e when $e - $s eq 2
return
avg($w)
(
<window>a b</window>,
<window>c 10</window>,
<window>20 30</window>
)
(4, 10, 14)
(4, 10)
Q: What do the following XQuery produce?
for sliding window $w in ("a", "b", "c", 10, 20, 30)
start at $s when fn:true()
end at $e when $e - $s eq 1
return
<window>{$w}</window>
for sliding window $w in (2, 4, 6, 8, 10, 12, 14)
start at $s when fn:true()
end at $e when $e - $s eq 2
return
avg($w)
for sliding window $w in (2, 4, 6, 8, 10, 12, 14)
start at $s when fn:true()
only end at $e when $e - $s eq 2
return
avg($w)
(
<window>a b</window>,
<window>b c</window>,
<window>c 10</window>,
<window>10 20</window>,
<window>20 30</window>,
<window>30</window>
)
(4, 6, 8, 10, 12, 13, 14)
(4, 6, 8, 10, 12)
The where clause serves as a filter within the FLWOR expression.
The condition of the WhereClause is evaluated once for each input tuple.
If the effective boolean value of the condition is true, the input tuple is included in the output tuple stream, otherwise (false) it is excluded.
WhereClause ::= "where" ExprSingle
Any WhereClause can alternatively be written as a Predicate on the input expression!
WhereClauses were introduced primarily to ease of adoption by SQL users!
Q: What do the following XQuery produce?
let $x := ("a", "b", "c")
let $y := (10, 20, 30)
where $x = "a"
return
($x, $y)
for $x in ("a", "b", "c")
let $y := (10, 20, 30)
where $x = "a"
return
($x, $y)
for $x in ("a", "b", "c")
let $y := (10, 20, 30)
where $x = "a" and $y = 10
return
($x, $y)
for $x in ("a", "b", "c")
let $y := (10, 20, 30)
where $x = "a"
where $y = 10
return
($x, $y)
for $x in ("a", "b", "c")
for $y in (10, 20, 30)
where $x = "a"
where $y = 10
return
($x, $y)
("a", "b", "c", 10, 20, 30)
("a", 10, 20, 30)
("a", 10, 20, 30)
("a", 10, 20, 30)
("a", 10)
The group by clause groups together one-or-more tuples from the input stream into a tuple in the
output stream.
GroupByClause ::= "group" "by" GroupingSpecList
GroupingSpecList ::= GroupingSpec ("," GroupingSpec)*
GroupingSpec ::= GroupingVariable (TypeDeclaration? ":=" ExprSingle)? ("collation" URILiteral)?
GroupingVariable ::= "$" VarName
Q: What do the following XQuery produce?
let $x := (10, 20, 30)
group by $y := $x < 30
return
$x
for $x in (10, 20, 30)
group by $y := $x < 30
return
$x
let $bargain-ceiling := 10
let $d :=
<items>
<item cost="101">Holiday Hamper</item>
<item cost="1">Banana</item>
<item cost="1">Apple</item>
<item cost="11">Truffle Cheese</item>
</items>
return
for $x in $d/item
let $is-bargain := $x/xs:integer(@cost) lt $bargain-ceiling
let $elem-name := if ($is-bargain) then "bargain" else "standard"
group by $is-bargain
return
element {$elem-name[1]} {
$x
}
(10, 20, 30)
((10, 20), 30)
(
<standard>
<item cost="101">Holiday Hamper</item>
<item cost="11">Truffle Cheese</item>
</standard>
,
<bargain>
<item cost="1">Banana</item>
<item cost="1">Apple</item>
</bargain>
)
XQuery 1.0, does not have a GroupBy Clause, however, you can improvise by using predicates.
You can could also use fn:distinct-values to find the distinct values for grouping your items.
declare variable $data := document {
<inventory>
<item dept="BED" cost="5.99" qty="27">Queen Size Fitted Bed Sheet</item>
<item dept="KIT" cost="21.99" qty="6">9-inch Saucepan</item>
<item dept="HOM" cost="5.99" qty="20">Table Cloth</item>
<item dept="BED" cost="31.25" qty="4">Bed-side Cabinet</item>
<item dept="KIT" cost="3.50" qty="15">Cheese Grater</item>
<item dept="KIT" cost="2.50" qty="3">Sieve</item>
</inventory>
};
let $items := $data//item
let $depts := distinct-values($items/@dept)
for $dept in $depts
let $dept-items := $items[@dept eq $dept]
order by $dept
return
<department totalQuantity="{sum($dept-items/@qty)}" code="{$dept}" numItems="{count($dept-items)}">
{$dept-items ! <item cost="{@cost}" qty="{@qty}">{text()}</item>}
</department>
The order by clause reorders the tuples from the input stream into the output tuple stream by
value.
OrderByClause ::= (("order" "by") | ("stable" "order" "by")) OrderSpecList
OrderSpecList ::= OrderSpec ("," OrderSpec)*
OrderSpec ::= ExprSingle OrderModifier
OrderModifier ::= ("ascending" | "descending")? ("empty" ("greatest" | "least"))? ("collation" URILiteral)?
An alternative introduced in XPath 3.0, can be to instead use the fn:sort function in some circumstances.
Q: What do the following XQuery produce?
let $x := (999, 7, 20)
order by $x ascending
return
$x
for $x in (999, 7, 20)
order by $x ascending
return
$x
let $d :=
<items>
<item cost="101">Holiday Hamper</item>
<item cost="1">Banana</item>
<item cost="1">Apple</item>
<item cost="11">Truffle Cheese</item>
</items>
return
for $x in $d/item
order by $x/@cost ascending
return
$x
let $d :=
<items>
<item cost="101">Holiday Hamper</item>
<item cost="1">Banana</item>
<item cost="1">Apple</item>
<item cost="11">Truffle Cheese</item>
</items>
return
<items>{
for $x in $d/item
order by $x/xs:decimal(@cost) ascending, $x ascending
return
$x
}</items>
Syntax error!
(7, 20, 999)
(
<item cost="1">Banana</item>,
<item cost="1">Apple</item>,
<item cost="101">Holiday Hamper</item>,
<item cost="11">Truffle Cheese</item>
)
(
<items>
<item cost="1">Apple</item>
<item cost="1">Banana</item>
<item cost="11">Truffle Cheese</item>
<item cost="101">Holiday Hamper</item>
</items>
)
The count clause binds a variable to the position of the current tuple in the tuple stream.
Q: How is this different to the PositionalVar of the ForClause?
PositionalVar!
CountClause ::= "count" "$" VarName
Q: What do the following XQuery produce?
for $x at $y in ("a", "b", "c")
count $c
return
<x y="{$y}" c="{$c}">{$x}</x>
for $x at $y in ("a", "b", "c")
order by $x descending
count $c
return
<x y="{$y}" c="{$c}">{$x}</x>
for $x at $y in ("a", "b", "c")
count $c1
order by $x descending
count $c2
return
<x y="{$y}" c1="{$c1}" c2="{$c2}">{$x}</x>
(
<x y="1" c="1">a</x>,
<x y="2" c="2">b</x>,
<x y="3" c="3">c</x>
)
(
<x y="3" c="1">c</x>,
<x y="2" c="2">b</x>,
<x y="1" c="3">a</x>
)
(
<x y="3" c1="3" c2="1">c</x>,
<x y="2" c1="2" c2="2">b</x>,
<x y="1" c1="1" c2="3">a</x>
)
The return is always the final clause in a FLWOR expression.
It is evaluated once for each tuple in the input stream.
The expression in the Return Clause, may itself be another FLWOR expression!
It allows you to easily compose FLWOR expressions!
ReturnClause ::= "return" ExprSingle
A comprehensive FLWOR expression(s) could look like:
let $d :=
<items>
<item cost="101">Holiday Hamper</item>
<item cost="1">Banana</item>
<item cost="1">Apple</item>
<item cost="11">Truffle Cheese</item>
</items>
return
let $items :=
for $x at $i in $d/item
let $cost := $x/xs:decimal(@cost)
where $cost le 100
order by $cost ascending, $x ascending
count $c
return
for $y in $x
let $new-cost := $cost * 1.5
let $id := substring(upper-case($y/text()), 1 ,3) || "-0001"
return
<item id="{$id}" cost="{$new-cost}" idx="{$c}" original-idx="{$i}">{$y/text()}</item>
return
<items count="{count($items)}">{$items}</items>
(
<items count="3">
<item id="APP-0001" cost="1.5" idx="1" original-idx="3">Apple</item>
<item id="BAN-0001" cost="1.5" idx="2" original-idx="2">Banana</item>
<item id="TRU-0001" cost="16.5" idx="3" original-idx="4">Truffle Cheese</item>
</items>
)
FLWOR expressions are the primary construct in XQuery
In XQuery 1.0, it consists of the following clauses:
In XQuery 3.0, it consists of the following clauses:
But... FLWGOCR expression doesn't sound as nice as FLWOR ('flower') expression!
Executing Querying in Elemental
XQuery FLWOR Expressions