Performance tuning of nested SELECT query - creating Nested XML

Partha Das 286 Reputation points
2022-08-25T10:16:43.453+00:00

Hi,

I have a SQL query

============================

SELECT OrderID, CustomerID, EmployeeID,
(select OrderDetails.OrderID, ProductID, UnitPrice, Quantity
from OrderDetails
WHERE OrderDetails.OrderID = Orders.OrderID FOR XML PATH('OrderDetails'), TYPE)
FROM Orders FOR XML PATH('Orders'), TYPE;

============================

This gives the result as attached 234853-result.xml

But this nested SELECT query is performing very slow - agreed. But is there any other way so that performance can be improved without distorting the nested XML output.

Schema of the DB is as below:
234882-db-design.jpg

Quick advice is highly appreciated.

Regards,
Partha

Azure SQL Database
Developer technologies | Transact-SQL
Developer technologies | Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
{count} votes

3 answers

Sort by: Most helpful
  1. Yitzhak Khabinsky 27,091 Reputation points
    2022-08-25T14:47:39.62+00:00

    Hi @Partha Das ,

    You need to check existence of indexes on the following columns:

    • Orders.OrderID
    • OrderDetails.OrderID

    Well-formed XML shall have a root element. That's why I added it via ROOT(...) clause to the SELECT statement below.

    SQL

    SELECT OrderID,  
           CustomerID,  
           EmployeeID,  
           (  
               SELECT OrderDetails.OrderID,  
                      ProductID,  
                      UnitPrice,  
                      Quantity  
               FROM OrderDetails  
               WHERE OrderDetails.OrderID = Orders.OrderID  
               FOR XML PATH('OrderDetails'), TYPE  
           )  
    FROM Orders  
    FOR XML PATH('Orders'), TYPE, ROOT('root');  
    

  2. Erland Sommarskog 128.7K Reputation points MVP Volunteer Moderator
    2022-08-25T21:43:40.623+00:00

    Very slow? When I run it on my copy of Northwind, the result is instant. When I run it on my extended version known as Northgale with a million orders, it takes a least a minute, but that is not that surprising.

    0 comments No comments

  3. LiHongMSFT-4306 31,616 Reputation points
    2022-08-26T03:16:29.307+00:00

    Hi @Partha Das
    How about using Outer Apply instead of subquery, like this:

    SELECT *,A.*  
    FROM Orders OUTER APPLY (SELECT OrderDetails.OrderID, ProductID, UnitPrice, Quantity  
    					     FROM OrderDetails  
    						 WHERE OrderDetails.OrderID = Orders.OrderID   
    	                     FOR XML PATH('OrderDetails'), TYPE ) AS A  
    FOR XML PATH('Orders'), TYPE, ROOT('Root');  
    

    Best regards,
    LiHong

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.