Variable scope in for and let clauses

A variable that is bound in a for or let clause is in scope for all of the sub-expressions of the FLWOR expression that appear after the variable binding. This means that a for or let clause can reference variables that are bound in earlier clauses or in earlier bindings in the same clause.
In the following example, a FLWOR expression has the following clauses:
  • A let clause that binds the variable $orders.
  • A for clause that references $orders and binds the variable $i.
  • Another let clause that references both $orders and $i and binds the variable $c.
The example finds all of the distinct item numbers in a set of orders, and returns the number of orders for each distinct item number.
let $orders := db2-fn:xmlcolumn("ORDERS.XMLORDER")
for $i in fn:distinct-values($orders/order/itemno)
let $c := fn:count($orders/order[itemno = $i])
return
<ordercount>
  <itemno> {$i} </itemno>
  <count> {$c} </count>
</ordercount>
Important: The for and let clauses of a FLWOR expression cannot bind the same variable name more than once.