XQuery - Basics - FLWOR Expressions

Thursday 12th November 2026

First Session: Learning Objectives

Lab: Our First XQuery

Our First XQuery

Your First XQuery

Challenges for you to implement in XQuery:

  1. What was the date one week ago?

  2. What was the date one month ago?

  3. What day was the 4th February 1981?

  4. How many days old are you?

Use the function xs:dayTimeDuration() and its friends!

Lab 1 Solution for Challenges

  1. What was the date one week ago?

    current-date() - xs:dayTimeDuration("P7D")
  2. What was the date one month ago?

    current-date() - xs:yearMonthDuration("P1M")
  3. What day was the 4th February 1981?

    fn:format-date(xs:date("1981-02-04"), "[FNn]")
  4. How many days old are you? (Substitute your birthday)!

    xs:date("1981-02-04") - current-date()

FLWOR Expressions

What is a FLWOR Expression?

For Clause


        ForClause        ::=  "for" ForBinding ("," ForBinding)*
        ForBinding       ::=  "$" VarName TypeDeclaration? AllowingEmpty? PositionalVar? "in" ExprSingle
        TypeDeclaration  ::=  "as" SequenceType
        AllowingEmpty    ::=  "allowing" "empty"
        PositionalVar    ::=  "at" "$" VarName
      
ForClause - EBNF for XQ 3.1

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!

For Clause - Examples

Q: What do the following XQuery produce?

  1. 
              for $x at $y in ("a", "b", "c")
              return
                $y || ":" || $x
            
  2. 
              let $d := ("a", "b", "c")
              for $x in $d, $y in $d
              return
                $x || ":" || $y
            
  3. 
              let $d := ("a", "b", "c")
              for $x in $d
              for $y in $d
              return
                concat($x, ":", $y)
            
  4. 
              for $x allowing empty at $y in ("a", "b", "c")[4]
              return
                $x || ":" || $y
            

For Clause - Examples - Solutions

  1. ("1:a", "2:b", "3:c")
  2. ("a:a", "a:b", "a:c", "b:a", "b:b", "b:c", "c:a", "c:b", "c:c")
  3. ("a:a", "a:b", "a:c", "b:a", "b:b", "b:c", "c:a", "c:b", "c:c")
  4. ":0"

Let Clause


        LetClause        ::=  "let" LetBinding ("," LetBinding)*
        LetBinding       ::=  "$" VarName TypeDeclaration? ":=" ExprSingle
        TypeDeclaration  ::=  "as" SequenceType
      
LetClause - EBNF for XQ 3.1

Let Clause - Examples

Q: What do the following XQuery produce?

  1. 
              let $x := ("a", "b", "c"), $y := (1, 2, 3)
              return
                string-join($x, ",") || ":" || string-join($y, ",")
            
  2. 
              let $x := ("a", "b", "c"),
              $y := (1, 2, 3)
              return
                $x => string-join(",") || ":" || $y => string-join(",")
            
  3. 
              let $x := ("a", "b", "c")
              $y := (1, 2, 3)
              return
                string-join($x, ",") || ":" || string-join($y, ",")
            
  4. 
              let $x := ("a", "b", "c")
              let $y := (1, 2, 3)
              return
                string-join((string-join($x, ","), string-join($y, ",")), ":")
            
  5. 
              let $x := ("a", "b", "c"),
              let $y := (1, 2, 3)
              return
                string-join($x, ",") || ":" || string-join($y, ",")
            

Let Clause - Examples - Solutions

  1. a,b,c:1,2,3
  2. a,b,c:1,2,3
  3. Syntax error!

  4. a,b,c:1,2,3
  5. Syntax error!

Window Clause


        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
      
WindowClause - EBNF for XQ 3.1

Tumbing Window Clause - Examples

Q: What do the following XQuery produce?

  1. 
             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>
           
  2. 
             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)
           
  3. 
             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)
           

Tumbling Window Clause - Examples - Solutions

  1. (
      <window>a b</window>,
      <window>c 10</window>,
      <window>20 30</window>
    )
  2. (4, 10, 14)
  3. (4, 10)

Sliding Window Clause - Examples

Q: What do the following XQuery produce?

  1. 
              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>
            
  2. 
              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)
            
  3. 
              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)
            

Sliding Window Clause - Examples - Solutions

  1. (
        <window>a b</window>,
        <window>b c</window>,
        <window>c 10</window>,
        <window>10 20</window>,
        <window>20 30</window>,
        <window>30</window>
    )
  2. (4, 6, 8, 10, 12, 13, 14)
  3. (4, 6, 8, 10, 12)

Where Clause


        WhereClause  ::=  "where" ExprSingle
      
WhereClause - EBNF for XQ 3.1

Any WhereClause can alternatively be written as a Predicate on the input expression!
WhereClauses were introduced primarily to ease of adoption by SQL users!

Where Clause - Examples

Q: What do the following XQuery produce?

  1. 
            let $x := ("a", "b", "c")
            let $y := (10, 20, 30)
            where $x = "a"
            return
              ($x, $y)
            
  2. 
            for $x in ("a", "b", "c")
            let $y := (10, 20, 30)
            where $x = "a"
            return
              ($x, $y)
            
  3. 
            for $x in ("a", "b", "c")
            let $y := (10, 20, 30)
            where $x = "a" and $y = 10
            return
              ($x, $y)
            
  4. 
            for $x in ("a", "b", "c")
            let $y := (10, 20, 30)
            where $x = "a"
            where $y = 10
            return
              ($x, $y)
            
  5. 
            for $x in ("a", "b", "c")
            for $y in (10, 20, 30)
            where $x = "a"
            where $y = 10
            return
              ($x, $y)
            

Where Clause - Examples - Solutions

  1. ("a", "b", "c", 10, 20, 30)
  2. ("a", 10, 20, 30)
  3. ("a", 10, 20, 30)
  4. ("a", 10, 20, 30)
  5. ("a", 10)

Group By Clause


        GroupByClause     ::=  "group" "by" GroupingSpecList
        GroupingSpecList  ::=  GroupingSpec ("," GroupingSpec)*
        GroupingSpec      ::=  GroupingVariable (TypeDeclaration? ":=" ExprSingle)? ("collation" URILiteral)?
        GroupingVariable  ::=  "$" VarName
      
GroupByClause - EBNF for XQ 3.1

Group By Clause - Examples

Q: What do the following XQuery produce?

  1. 
              let $x := (10, 20, 30)
              group by $y := $x < 30
              return
                $x
            
  2. 
              for $x in (10, 20, 30)
              group by $y := $x < 30
              return
                $x
            
  3. 
              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
                }
            

GroupBy Clause - Examples - Solutions

  1. (10, 20, 30)
  2. ((10, 20), 30)
  3. (
    <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>
    )

Detour - Grouping in XQuery version 1.0

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>
      
Example of Grouping in XQuery 1.0

Order By Clause


        OrderByClause  ::=  (("order" "by") | ("stable" "order" "by")) OrderSpecList
        OrderSpecList  ::=  OrderSpec ("," OrderSpec)*
        OrderSpec	    ::=  ExprSingle OrderModifier
        OrderModifier	::=  ("ascending" | "descending")? ("empty" ("greatest" | "least"))? ("collation" URILiteral)?
      
OrderByClause - EBNF for XQ 3.1

An alternative introduced in XPath 3.0, can be to instead use the fn:sort function in some circumstances.

Order By Clause - Examples

Q: What do the following XQuery produce?

  1. 
              let $x := (999, 7, 20)
              order by $x ascending
              return
                $x
            
  2. 
              for $x in (999, 7, 20)
              order by $x ascending
              return
                $x
            
  3. 
              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
            
  4. 
              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>
            

Order By Clause - Examples - Solutions

  1. Syntax error!

  2. (7, 20, 999)
  3. (
      <item cost="1">Banana</item>,
      <item cost="1">Apple</item>,
      <item cost="101">Holiday Hamper</item>,
      <item cost="11">Truffle Cheese</item>
    )
  4. (
      <items>
        <item cost="1">Apple</item>
        <item cost="1">Banana</item>
        <item cost="11">Truffle Cheese</item>
        <item cost="101">Holiday Hamper</item>
      </items>
    )

Count Clause


        CountClause  ::=  "count" "$" VarName
      
CountClause - EBNF for XQ 3.1

Count Clause - Examples

Q: What do the following XQuery produce?

  1. 
              for $x at $y in ("a", "b", "c")
              count $c
              return
                <x y="{$y}" c="{$c}">{$x}</x>
            
  2. 
              for $x at $y in ("a", "b", "c")
              order by $x descending
              count $c
              return
                <x y="{$y}" c="{$c}">{$x}</x>
            
  3. 
              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>
            

Count Clause - Examples - Solutions

  1. (
      <x y="1" c="1">a</x>,
      <x y="2" c="2">b</x>,
      <x y="3" c="3">c</x>
    )
  2. (
      <x y="3" c="1">c</x>,
      <x y="2" c="2">b</x>,
      <x y="1" c="3">a</x>
    )
  3. (
      <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>
    )

Return Clause


        ReturnClause  ::=  "return" ExprSingle
      
ReturnClause - EBNF for XQ 3.1

Return Clause - Example

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>
    

Return Clause - Example - Solution

  1. (
      <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 Expression Summary

First Session: What have we learned?