XQuery Notes

This post continues my notes from Introduction to Databases, a MOOC taught by Stanford’s Jennifer Widom. The topic of this post is XQuery.

XQuery Defition

XQuery is a query and functional programming language that is designed to query collections of XML data.

XQuery Syntax: FLWOR

FLWOR Syntax
1
2
3
4
5
for $var in expr
let $var := expr
where expr
order by expr
return expr

A couple examples

An example with last posts countries.xml file:

FLWOR Syntax
1
2
3
4
for $c in doc('countries.xml')/countries/country
where $c/@population > 100000000
order by $c/@population
return $c/@name

Grab countries with a city larger than 10,000,000:

FLWOR Syntax
1
2
3
4
for $c in doc('countries.xml')/countries/country
where $c/city/population > 10000000
order by $c/@name
return $c/@name

All of the expr in the syntax can be XPath expressions. The FLWOR syntax should be simple to pick up for anyone familiar with scripting languages or SQL.