Comparing SQL Syntax with XQuery Syntax

This section compares SQL syntax with XQuery syntax in order to give readers already familiar with SQL a jumpstart on learning XQuery. If you notice similarities between SQL and XQuery, it is not a coincidence; some of the key developers of the SQL standard also worked on the XQuery standard. Not all SQL syntax is covered in this chapter, only the most commonly used constructs.

A Simple Query

To compare SQL and XQuery queries, will we first start with our simple product catalog document. A basic SQL query might select all the values from the table that meet some specific criteria, for example those in the ACC department. The SQL statement that accomplishes this is:

select * from catalog
where dept='ACC'

In XQuery, we can use a straight path expression for such a simple query, as in:

doc("catalog2.xml")//product[@dept='ACC']

If you don't want to sort your results or construct new elements, it is often simpler (and possibly faster) to just use a path expression. However, we could also use a full FLWOR expression that uses a where clause similar to SQL, as in:

for $prod in doc("catalog2.xml")//product
where $prod/@dept='ACC'
return $prod

In the where clause, we need to start the reference to the dept attribute with $prod/ in order to give it some context. This is different from SQL, where if there is only one dept column in the table(s) in the query, it is assumed to be that one column. In XQuery, you must be explicit about where the dept attribute ...

Get XQuery now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.