XQuery Sequence Functions Tutorial 🎯

beginner
17 min

XQuery Sequence Functions Tutorial 🎯

Welcome to this comprehensive guide on XQuery Sequence Functions! By the end of this lesson, you'll have a solid understanding of these powerful tools that help manipulate and extract data from XML documents.

Let's start from the basics.

What are XQuery Sequence Functions? 📝

XQuery Sequence Functions are a collection of built-in functions in XQuery that operate on sequences, such as nodes, items, and atomic values. They are used to perform various operations like filtering, sorting, and calculating values.

Understanding Sequences 💡

Before diving into the functions, let's clarify what a sequence is in XQuery. A sequence is an ordered collection of zero or more items, where each item can be a node, atomic value, or another sequence.

Common XQuery Sequence Functions 🎯

Now, let's explore some commonly used XQuery Sequence Functions.

count() 📝

The count() function returns the number of items in a sequence.

xml
<xq:sequence select="count(//book)"/>

In this example, //book returns all the book elements in the XML document, and count() counts the number of those elements.

sum() 💡

The sum() function adds up all the numeric values in a sequence.

xml
<xq:sequence select="sum(//book/price)"/>

Here, //book/price selects all the price elements under book, and sum() calculates their total sum.

min(), max(), avg() 🎯

These functions find the minimum, maximum, and average values in a sequence, respectively.

xml
<xq:sequence select="min(//book/price)"/> <xq:sequence select="max(//book/price)"/> <xq:sequence select="avg(//book/price)"/>

These examples select the minimum, maximum, and average price of books in the XML document.

distinct-values() 💡

The distinct-values() function returns a sequence containing only unique values from the input sequence.

xml
<xq:sequence select="distinct-values(//book/category)"/>

This example returns a sequence with unique book categories from the XML document.

reverse() 🎯

The reverse() function reverses the order of the items in a sequence.

xml
<xq:sequence select="reverse(//book)"/>

This example returns the books in the XML document in reverse order.

Practical Example 💡

Let's put these functions into practice with a simple XML document containing book information:

xml
<books> <book id="1"> <title>Book 1</title> <price>10.99</price> <category>Fiction</category> </book> <book id="2"> <title>Book 2</title> <price>15.99</price> <category>Non-fiction</category> </book> <book id="3"> <title>Book 3</title> <price>8.99</price> <category>Fiction</category> </book> </books>

Using the functions we've learned, we can query this document to extract various pieces of information.

Quiz Time! 🎯

Quick Quiz
Question 1 of 1

What does the `count()` function do in XQuery?

Stay tuned for more in-depth lessons on XQuery and its various features! 🚀