XQuery Syntax and Expressions
Estimated study time: 14 minutes.
Most real-world XQuery code is built around the FLWOR expression — a structured pattern named after its five clauses: For, Let, Where, Order by, Return.
For Clause
for $course in doc("courses.xml")//course
return $course/title
Iterates over each matching node, similar to a loop.
Let Clause
let $allCourses := doc("courses.xml")//course
return count($allCourses)
Binds a variable to a value or a node set, without iterating.
Where Clause
for $course in doc("courses.xml")//course
where $course/@level = "beginner"
return $course/title
Filters the results, just like SQL's WHERE.
Order By Clause
for $course in doc("courses.xml")//course
order by $course/title
return $course/title
Sorts the returned results.
Constructing New XML
for $course in doc("courses.xml")//course
return <summary>{$course/title/text()}</summary>
XQuery lets you build brand-new XML elements directly inside the query, embedding selected values with curly braces.
💡 Tip: Write the
for and return clauses first to confirm you're selecting the right nodes, then add where and order by once the basic query works.