SQL Server XML Data Type

Estimated study time: 16 minutes. Store and query semi-structured data natively.

SQL Server offers a native XML data type that lets you store an entire XML document or fragment inside a single column, then query and modify it using built-in methods instead of treating it as plain text.

Creating a Column with XML Data Type

CREATE TABLE ProductCatalog (
  ProductID INT PRIMARY KEY,
  ProductDetails XML
);

Inserting XML Data

INSERT INTO ProductCatalog (ProductID, ProductDetails)
VALUES (1, '<Product><Name>Laptop</Name><Price>55000</Price></Product>');

Typed vs Untyped XML

An XML column can be untyped (any well-formed XML is accepted) or typed, where it's bound to an XML schema collection so SQL Server can validate the structure on insert.

CREATE XML SCHEMA COLLECTION ProductSchema AS N'...';
CREATE TABLE ProductCatalog (
  ProductDetails XML(ProductSchema)
);

Querying XML with .value()

The .value() method extracts a scalar value from an XML node.

SELECT ProductDetails.value('(/Product/Name)[1]', 'VARCHAR(100)') AS ProductName
FROM ProductCatalog;

Querying XML with .query()

The .query() method returns an XML fragment matching an XQuery expression.

SELECT ProductDetails.query('/Product/Name') AS NameNode
FROM ProductCatalog;

Modifying XML with .modify()

The .modify() method lets you insert, update, or delete nodes inside stored XML using XML DML.

UPDATE ProductCatalog
SET ProductDetails.modify('replace value of (/Product/Price/text())[1] with "59000"')
WHERE ProductID = 1;

Shredding XML with .nodes()

The .nodes() method turns XML nodes into a rowset, which is useful for joining XML data with relational tables.

SELECT T.c.value('.', 'VARCHAR(50)') AS Tag
FROM ProductCatalog
CROSS APPLY ProductDetails.nodes('/Product/*') AS T(c);
💡 Tip: Index an XML column with a primary or secondary XML index if you query it frequently — otherwise SQL Server has to shred the XML on every query, which gets slow on large documents.

Filtering Rows with exist()

The .exist() method returns 1 when an XQuery expression finds a match and 0 when it does not. It is the natural choice in a WHERE clause, and it can use XML indexes well.

-- products whose price is above 50000
SELECT ProductID
FROM ProductCatalog
WHERE ProductDetails.exist('/Product[Price > 50000]') = 1;

-- products that have a Warranty element at all
SELECT ProductID
FROM ProductCatalog
WHERE ProductDetails.exist('/Product/Warranty') = 1;

To filter on a value that comes from a variable or another column, pass it into the XQuery with sql:variable("@limit") or sql:column("t.Col") instead of building the query string by hand. This keeps the plan reusable and avoids injection through concatenated text.

You could write the same check with .value(), but .exist() avoids converting every node to a SQL type just to compare it.

Creating XML Indexes

A primary XML index stores a pre-shredded copy of the XML so queries do not parse the documents each time. The table must have a clustered primary key first. Secondary indexes then speed up specific query patterns.

CREATE PRIMARY XML INDEX PXML_ProductDetails
    ON ProductCatalog (ProductDetails);

-- helps path-based queries such as exist('/Product/Warranty')
CREATE XML INDEX IXML_ProductDetails_Path
    ON ProductCatalog (ProductDetails)
    USING XML INDEX PXML_ProductDetails FOR PATH;

Secondary index types are PATH, VALUE and PROPERTY. Indexes take extra storage and slow down inserts and updates, so add them only for columns you query often.

Producing XML from Relational Data

The reverse direction is just as common: building XML from normal tables for an export or an external system. FOR XML PATH gives fine control over element names.

SELECT p.ProductID AS "@id",
       p.Name      AS "Name",
       p.Price     AS "Price"
FROM dbo.Products AS p
FOR XML PATH('Product'), ROOT('Catalog'), TYPE;

The @id alias becomes an attribute, the other columns become child elements, and TYPE returns a real XML value rather than text. When XML uses namespaces, declare them with WITH XMLNAMESPACES before the query, or path expressions will return nothing.

Choosing XML, JSON or Normal Columns

OptionGood fitWatch out for
Relational columnsData you filter, join and aggregate oftenRigid when attributes vary a lot
XML typeDocuments exchanged with XML-based systems, schema validation needsVerbose storage, XQuery learning curve
JSON in NVARCHAR or the native JSON typeWeb APIs and flexible attributesNo schema enforcement by default

Common mistakes: forgetting the [1] singleton in .value() paths, which causes an error; storing XML in VARCHAR, which loses validation and the built-in methods; and using XML for data that clearly belongs in normal rows and columns. A good habit is to shred XML into tables once on arrival when the data will be reported on regularly.

Ready to go beyond the basics?

Get hands-on training, live mentorship, and placement support with Uncodemy's Data Analytics Course.

Explore Data Analytics Course →