Comparison of methods for querying XML data

Because XML data can be queried in a number of ways, using XQuery, SQL, or a combination of these, the method to choose can differ depending on your situation. The following sections describe conditions that are advantageous for a particular query method.

XQuery only

Querying with XQuery alone can be a suitable choice when:
  • applications access only XML data, without the need to query non-XML relational data
  • migrating queries previously written in XQuery to Db2®
  • returning query results to be used as values for constructing XML documents
  • the query author is more familiar with XQuery than SQL

XQuery that invokes SQL

Querying with XQuery that invokes SQL can be a suitable choice when (in addition to the scenarios identified in the previous section on using XQuery only):
  • queries involve XML data and relational data; SQL predicates and indexes defined on the relational columns can be leveraged in the query
  • you want to apply XQuery expressions to the results of:
    • UDF calls, as these cannot be invoked directly from XQuery
    • XML values constructed from relational data using SQL/XML publishing functions
    • queries that use Db2 Net Search Extender which offers full text search of XML documents but which must be used with SQL

SQL only

When retrieving XML data using only SQL, without any XQuery, you can query only at the XML column level. For this reason, only entire XML documents can be returned from the query. This usage is suitable when:
  • you want to retrieve entire XML documents
  • you do not need to query based on values within the stored documents, or where the predicates of your query are on other non-XML columns of the table

SQL/XML functions that execute XQuery expressions

The SQL/XML functions XMLQUERY and XMLTABLE, as well as the XMLEXISTS predicate, enable XQuery expressions to be executed from within the SQL context. Executing XQuery within SQL can be a suitable choice when:
  • existing SQL applications need to be enabled for querying within XML documents. To query within XML documents, XQuery expressions need to be executed, which can be done using SQL/XML
  • applications querying XML data need to pass parameter markers to the XQuery expression. (The parameter markers are first bound to XQuery variables in XMLQUERY or XMLTABLE.)
  • the query author is more familiar with SQL than XQuery
  • both relational and XML data needs to be returned in a single query
  • you need to join XML and relational data
  • you want to group or aggregate XML data. You can apply the GROUP BY or ORDER BY clauses of a subselect to the XML data (for example, after the XML data has been retrieved and collected in table format by using the XMLTABLE function)