fn:position function

The fn:position function returns the position of the context item in the sequence that is currently being processed.

The position function is typically used in a predicate. However it can also be used to produce the position of each occurrence of its context item.

Syntax

Read syntax diagramSkip visual syntax diagramfn:position()

Returned value

The returned value is an xs:integer value that indicates the position of the context item in the sequence that is currently being processed. The first item in the sequence has position 1. If the context item is undefined, an error is returned. The position function returns a deterministic result only if the sequence that contains the context item has a deterministic order.

In the following cases, an error is returned:
  • The context step is the descendant or descendant-or-self axis
  • The context is a sequence of atomic values
  • fn:position occurs as part of a nested filter expression within a predicate. I
    $x/a[$y/c/fn:position()] $x/a[(b/c)[2]]

Examples

The following query returns one row that contains an XML column with the second element in the sequence of <c> elements in the document.

<x xmlns="http://posample.org"><b><c>x</c><c>y</c><c>z</c></b></x>

SELECT * FROM 
     XMLTABLE(XMLNAMESPACES(DEFAULT 'http://posample.org'), 
              '$d/x/b/c[fn:position()=2]'
              PASSING XMLPARSE(DOCUMENT '<x xmlns="http://posample.org">
                                         <b><c>x</c><c>y</c><c>z</c></b></x>') AS "d"
              COLUMNS RESULT XML PATH '.') X

The returned value is <c>y</c>.

The following query returns the position of each occurrence of <a><b><c> as a single XML value.

SELECT * FROM            
     XMLTABLE('.'                        
              PASSING XMLPARSE(DOCUMENT                           
                       '<a><b><c>c1</c></b><b><c>c2</c><c>c3</c></b></a>')
              COLUMNS RESULT_POS XML PATH '/a/b/c/fn:position()') X                             

The returned value is "1 2 3".