fn:last function

The fn:last function returns the number of values in the sequence of items that is currently being processed.

Syntax

Read syntax diagramSkip visual syntax diagramfn:last()

Returned value

If the sequence that is currently being processed is not the empty sequence, the returned value is an xs:integer value that is the number of values in the sequence. If the sequence that is currently being processed is the empty sequence, the returned value is the empty sequence.

In the following cases, an error is returned:
  • fn:last is separated from its context item by "/" or "//".
    For example, the following expressions are not supported:
    /a/b/c/fn:last
    /a/b/[c/fn:last=3]
  • The context node has a descendant axis or descendant-or-self axis.
    For example, the following expression is not supported:
    /a/b/descendant::c[fn:last()=1]
  • The context node is a filter expression, and the filter expression has a step with a descendant axis or descendant-or-self axis, or a nested filter expression.
    For example, the following expression is not supported:
    /a/(b/descendant::c)[fn:last()=1]

Example

In the sample CUSTOMER table, the customer document for customer 1003 looks like this:

<customerinfo xmlns="http:⁄⁄posample.org" Cid="1003">
  <name>Robert Shoemaker<⁄name>
  <addr country="Canada">
    <street>1596 Baseline<⁄street>
    <city>Aurora<⁄city>
    <prov-state>Ontario<⁄prov-state>
    <pcode-zip>N8X-7F8<⁄pcode-zip>
  <⁄addr>
  <phone type="work">905-555-7258<⁄phone>
  <phone type="home">416-555-2937<⁄phone>
  <phone type="cell">905-555-8743<⁄phone>
  <phone type="cottage">613-555-3278<⁄phone>
<⁄customerinfo>

The following query retrieves the last phone number in the document. The query calls the fn:last function to determine the number of phone number items, and then uses the fn:last result to point to the last phone number.

SELECT                                                            
 XMLQUERY('declare default element namespace "http://posample.org";
 $X/customerinfo/phone[fn:last()]'                                
 PASSING INFO AS "X") FROM CUSTOMER WHERE CID=1003               

The returned value is <phone type="cottage">613-555-3278<⁄phone>.