How Query XML Data Type in SQL Server?


Larry Thompson

In this tutorial, we will explore how to query XML data type in SQL Server. The XML data type allows you to store and manipulate XML data in your database. By using SQL Server’s powerful XML querying capabilities, you can easily extract and manipulate data within your XML documents.

What is the XML data type?
The XML data type is a built-in data type in SQL Server that allows you to store XML documents in a column of a table. It provides a flexible way to handle and query XML data within the database.

Creating a table with an XML column
To start working with the XML data type, you need to create a table that includes an XML column. Here’s an example of how you can do this:

Data XML

In this example, we have created a table called “MyTable” with two columns: “ID” of type INT and “Data” of type XML. The “Data” column will store our XML documents.

Inserting XML data into the table
Once you have your table ready, you can insert XML data into it. Here’s an example of how you can insert an XML document into the “Data” column:

INSERT INTO MyTable (ID, Data)
VALUES (1, ‘SQL BasicsJohn Doe‘);

In this example, we are inserting an XML document representing a bookstore into our table.

Querying the XML data

Now that we have our table set up and populated with some sample data, let’s explore how we can query the XML data.

Extracting values from the XML
To extract values from an XML document stored in the database, you can use the “value” method. Here’s an example:

Data.value(‘(/bookstore/book/title)[1]’, ‘varchar(100)’) AS Title,
Data.value(‘(/bookstore/book/author)[1]’, ‘varchar(100)’) AS Author

In this example, we are using the “value” method to extract the title and author from each book in our XML document.

Filtering XML data
You can also filter XML data based on specific criteria.value(‘(/bookstore/book[price > 10]/title)[1]’, ‘varchar(100)’) AS Title,
Data.value(‘(/bookstore/book[price > 10]/author)[1]’, ‘varchar(100)’) AS Author

In this example, we are filtering the XML data to retrieve only the books with a price greater than 10.


In this tutorial, we have learned how to query XML data type in SQL Server. We explored how to create a table with an XML column, insert XML data into it, and perform various operations on the XML data using SQL Server’s powerful querying capabilities.

By leveraging the XML data type and its querying capabilities, you can efficiently work with and manipulate XML data within your SQL Server database. So go ahead and start exploring the possibilities of handling XML data in your SQL Server applications!

Discord Server - Web Server - Private Server - DNS Server - Object-Oriented Programming - Scripting - Data Types - Data Structures

Privacy Policy