I'm running a query that is processing some nodes out of an XML document. My estimated subtree cost is in the millions and it seems it all comes from a sort operation sql server is performing on some data that I extract from xml columns via XPath. The Sort operation has an estimated number of rows to be around 19 million, whereas the actual row count is about 800. The query itself runs reasonably well (1 - 2 seconds), but the discrepancy has me wondering about the query performance and why this difference is so large?
- Anybody can ask a question
- Anybody can answer
- The best answers are voted up and rise to the top
There is no statistics generated on XML columns. The estimates is guessed based on the expressions used when querying the XML.
Using this table:
And this rather simple XML query:
Will give you one row returned but the estimated rows returned is 200. It will be 200 regardless of what XML or how much XML you stuff into the XML column for that one row.
This is the query plan with the estimated row count displayed.
A way to improve, or at least change, the estimates is to give the query optimizer some more information about the XML. In this case, because I know that
That will give me an estimate of 5 rows returned.
The rewrite of the query will probably not speed up the shredding of the XML but if the estimates are better, chances are that the query optimizer can make smarter decisions for the rest of the query.
I have not found any documentation on what the rules are for the estimates other than a presentation by Michael Rys that says "Base cardinality estimate is always 10’000 rows!".