The last function in XQuery is used to determine the position number of the last item in
the current context node list during the evaluation of an expression. It is particularly
useful within XPath expressions and FLWOR loops to determine the size or to operate on the
last item of a sequence.
Syntax
fn:last()
The
last
function does not take any parameters. It operates within a
context, usually within XPath expressions or FLWOR (For, Let, Where, Order by,
Return) expressions.
Return Value
Returns the context size from the dynamic context.
It returns the integer position of the last item in the current context sequence. If
you are iterating over a sequence,
last()
provides the total number
of items in that sequence.
Examples
The following table lists some sample queries and return values:
SAMPLE FUNCTION
OUTPUT
let $doc :=
<items>
<item>Apple</item>
<item>Banana</item>
<item>Cherry</item>
</items>
(: Select the last <item> :)
let $lastItem := $doc/item[position() = fn:last()]
(: Select all but the last <item> :)
let $allButLast := $doc/item[position() lt fn:last()]
return
<results>
<last-item>{$lastItem/text()}</last-item>
<all-but-last>{ $allButLast/text() }</all-but-last>
</results>