Parentheses and subscripts

Subscripts apply to the expression that immediately precedes them. Use parentheses to group expressions in a path. The examples in this section illustrate the use of parentheses with subscripts.

The following general example, which does not use subscripts, returns all titles in the book element.

select xmlextract(’/bookstore/book/title’, text_doc) from sample_docs where name_doc=’bookstore’
--------------------------------
<title>Seven Years in Trenton</title>
<title>History of Trenton</title>
<title>Tracking Trenton</title>
<title>Treanton Today, Trenton Tomorrow</title>
<title>Whos Who in Trenton</title>

To list only the first title, you can use the “[1]” subscript, and enter this query:

select xmlextract
(’/bookstore/book/title[1]’, text_doc)
from sample_docs where name_doc=’bookstore’
------------------------------------------------
<title>Seven Years in Trenton</title>
<title>History of Trenton</title>
<title>Tracking Trenton</title>
<title>Treanton Today, Trenton Tomorrow</title>
<title>Whos Who in Trenton</title>

However, the above query does not return the first title in the bookstore. It returns the first title in each book. Similarly, the following query, which uses the “[2]” subscript, returns the second title of each book, not the second title in the bookstore. Because no book has more than one title, the result is empty.

select xmlextract
(’/bookstore/book/title[2]’, text_doc) 
from sample_docs where name_doc=’bookstore’
---------------------------------
NULL

These queries return the ith title in the book, rather than in the bookstore, because the subscript operation (and predicates in general) applies to the immediately preceding item. To return the second title in the overall bookstore, rather than in the book, use parentheses around the element to which the subscript applies. For example:

select smlextract
(’(/bookstore/booktitle)[2]’, text_doc) 
from sample_docs where name_doc=’bookstore’
---------------------------------------------
<title>History of Trenton</title>

You can group any path with parentheses. For example:

select xmlextract(’(//title)[2]’, text_doc)
from sample_docs where name_doc=’bookstore’
----------------------------------------------
<title>History of Trenton</title>