{"id":2671,"date":"2014-10-21T15:48:30","date_gmt":"2014-10-21T22:48:30","guid":{"rendered":"http:\/\/3.209.169.194\/blogs\/kimberly\/?p=2671"},"modified":"2014-10-23T10:28:47","modified_gmt":"2014-10-23T17:28:47","slug":"multi-column-statistics-exponential-backoff","status":"publish","type":"post","link":"https:\/\/www.sqlskills.com\/blogs\/kimberly\/multi-column-statistics-exponential-backoff\/","title":{"rendered":"Multi-column statistics and exponential backoff"},"content":{"rendered":"<p>After writing <a href=\"https:\/\/www.sqlskills.com\/blogs\/kimberly\/sqlskills-procs-analyze-data-skew-create-filtered-statistics\/\">SQLskills procs to analyze data skew and create filtered statistics<\/a>, I received a couple of emails asking me to further explain the sentence &#8220;This is also true for multi-column, column statistics (where you need to use MORE than just the first column) and hypothetical indexes created with auto pilot.&#8221; (NOTE: <em><strong>this<\/strong> <\/em>refers to the fact that these don&#8217;t work in the new CE.)<\/p>\n<p>So, in this post, I want to further explain multi-column statistics and how both the legacy and new CE would calculate selectivity using the Credit sample database. If you don&#8217;t have a copy of this, you can download a SQL Server 2008 backup from <a href=\"https:\/\/www.sqlskills.com\/sql-server-resources\/sql-server-demos\/\">here<\/a>. To reproduce everything shown in this example, you must restore this to SQL Server 2014. FYI &#8211; at the time of this blog post, I&#8217;m running SQL Server 2014 CU3 (version = 12.0.2402.0).<\/p>\n<h2>What CE Model are you running?<\/h2>\n<p>Review the default cardinality estimation model used across all of your databases:<\/p>\n<pre class=\"brush: sql; title: ; toolbar: true; wrap-lines: true; notranslate\" title=\"\">\r\nSELECT\u00a0 [name] AS 'Database Name'\r\n\u00a0\u00a0\u00a0 , CASE\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 WHEN [compatibility_level] = 120 THEN 'New SQL Server 2014 CE Model'\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 ELSE 'Legacy CE Model'\r\n\u00a0\u00a0\u00a0\u00a0\u00a0 END AS 'Cardinality Estimation Model'\r\nFROM\u00a0\u00a0\u00a0 [sys].[databases];\r\nGO\r\n<\/pre>\n<h2>What does the Legacy CE Model use if there are multi-column statistics?<\/h2>\n<p>Check out the indexes and statistics on the charge table:<\/p>\n<pre class=\"brush: sql; title: ; toolbar: true; wrap-lines: true; notranslate\" title=\"\">\r\nEXEC [sp_helpstats] '[dbo].[charge]', 'all';\r\nGO\r\n<\/pre>\n<p>You should see that there are ONLY statistics on existing indexes:<\/p>\n<pre class=\"brush: plain; gutter: false; title: ; toolbar: true; wrap-lines: true; notranslate\" title=\"\">\r\nstatistics_name\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 statistics_keys\r\n------------------------ ------------------\r\ncharge_category_link\u00a0\u00a0\u00a0\u00a0 category_no\r\ncharge_provider_link\u00a0\u00a0\u00a0\u00a0 provider_no\r\ncharge_statement_link\u00a0\u00a0\u00a0 statement_no\r\nChargePK\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 charge_no\r\n<\/pre>\n<p>We&#8217;re going to run some queries against the charge table and we&#8217;re going to query against the category_no and the provider_no columns&#8230; while indexes for category_no and provider_no might be helpful, I want to drop those and just see how the estimates work with multi-column, column statistics:<\/p>\n<pre class=\"brush: sql; title: ; toolbar: true; wrap-lines: true; notranslate\" title=\"\">\r\nDROP INDEX [charge].[charge_provider_link];\r\nDROP INDEX [charge].[charge_category_link];\r\nGO\r\n<\/pre>\n<p>Without those indexes, SQL Server does not have any column-level statistics for the category_no or provider_no columns. To help the queries we&#8217;re going to run, we&#8217;ll create a multi-column, column statistic:<\/p>\n<pre class=\"brush: sql; title: ; toolbar: true; wrap-lines: true; notranslate\" title=\"\">\r\nCREATE STATISTICS [TestStat]\r\nON [dbo].[charge] ([provider_no], [category_no]);\r\nGO\r\n<\/pre>\n<p>Now, we&#8217;ll see what happens when we run a query using the legacy CE model vs. the new CE model. Be sure to turn on &#8220;Show Actual Execution Plan&#8221; in the Query drop-down menu.<\/p>\n<pre class=\"brush: sql; title: ; toolbar: true; wrap-lines: true; notranslate\" title=\"\">\r\nSELECT [ch].*\r\nFROM [dbo].[charge] AS [ch]\r\nWHERE [ch].[provider_no] = 434\r\n\u00a0\u00a0\u00a0 AND [ch].[category_no] = 10\r\nOPTION (QUERYTRACEON 9481, QUERYTRACEON 3604, QUERYTRACEON 9204, RECOMPILE);\r\nGO -- TF 9481 = CardinalityEstimationModelVersion 70<\/pre>\n<p>Looking at the showplan: <a href=\"https:\/\/www.sqlskills.com\/blogs\/kimberly\/wp-content\/uploads\/2014\/10\/PlanEstimate_withArrows.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-2672 size-full\" src=\"https:\/\/www.sqlskills.com\/blogs\/kimberly\/wp-content\/uploads\/2014\/10\/PlanEstimate_withArrows.jpg\" alt=\"Plan&amp;Estimate_withArrows\" width=\"1920\" height=\"1080\" srcset=\"https:\/\/www.sqlskills.com\/blogs\/kimberly\/wp-content\/uploads\/2014\/10\/PlanEstimate_withArrows.jpg 1920w, https:\/\/www.sqlskills.com\/blogs\/kimberly\/wp-content\/uploads\/2014\/10\/PlanEstimate_withArrows-300x168.jpg 300w, https:\/\/www.sqlskills.com\/blogs\/kimberly\/wp-content\/uploads\/2014\/10\/PlanEstimate_withArrows-1024x576.jpg 1024w, https:\/\/www.sqlskills.com\/blogs\/kimberly\/wp-content\/uploads\/2014\/10\/PlanEstimate_withArrows-900x506.jpg 900w\" sizes=\"auto, (max-width: 1920px) 100vw, 1920px\" \/><\/a>You can see the estimate and the actual are fairly close (but, by no means perfect). To understand where this comes from &#8211; you need to understand the density vector component of a statistic:<\/p>\n<pre class=\"brush: sql; title: ; toolbar: true; wrap-lines: true; notranslate\" title=\"\">\r\nDBCC SHOW_STATISTICS ('[dbo].[charge]', 'TestStat')\r\nWITH DENSITY_VECTOR;\r\nGO\r\n<\/pre>\n<p>The &#8220;All density&#8221; columns can be used to calculate the average number of rows that are returned when that column (or, combination of columns &#8211; as you add the second, third, etc. columns &#8211; shown as rows [when present] in the density vector). And, the column &#8220;Columns&#8221; shows the combination. For another example, if we had created a statistic on columns such as Lastname, Firstname, and Middleinitial then the all density could help us understand the average number of rows returned when supplying just a lastname; or, when supplying both a lastname AND a firstname; or, finally, when supplying a lastname, firstname, and middleinitial. What the density vector does not provide is a way of knowing the selectivity of any of the secondary columns on their own; it knows ONLY of the left-based combinations. This is one of the reasons why column-level statistics are helpful; they can provide the densities of the secondary columns on their own.<\/p>\n<p>For this query, we&#8217;re going to use the &#8220;All density&#8221; of the combination of\u00a0 provider_no and category_no (from the 2nd row of output). The &#8220;All density&#8221; value is 0.0002914602. If we multiple that by the number of rows in the table (at the time the statistics were created) then we can get the average number of rows returned. To see the number of rows in the table, we need to review the statistics_header component as well as the density_vector. This is easiest by re-running our DBCC command without the WITH clause.<\/p>\n<pre class=\"brush: sql; title: ; toolbar: true; wrap-lines: true; notranslate\" title=\"\">\r\nDBCC SHOW_STATISTICS ('[dbo].[charge]', 'TestStat');\r\nGO\r\n<\/pre>\n<p>The result is to multiply the &#8220;All density&#8221; of 0.0002914602\u00a0times 1600000 rows for an average of: 466.3363200000 (this is where the estimate of 466.336 is calculated).<\/p>\n<h2>What about the New CE Model in SQL Server 2014?<\/h2>\n<p>First, we&#8217;ll re-run the query but force the new CE model using trace flag 2312:<\/p>\n<pre class=\"brush: sql; title: ; toolbar: true; wrap-lines: true; notranslate\" title=\"\">\r\nSELECT [ch].*\r\nFROM [dbo].[charge] AS [ch]\r\nWHERE [ch].[provider_no] = 434\r\nAND [ch].[category_no] = 10\r\nOPTION (QUERYTRACEON 2312, QUERYTRACEON 3604, QUERYTRACEON 9204, RECOMPILE);\r\nGO -- TF 2312 = CardinalityEstimationModelVersion 120\r\n<\/pre>\n<p><a href=\"https:\/\/www.sqlskills.com\/blogs\/kimberly\/wp-content\/uploads\/2014\/10\/PlanEstimate_2014CE_withArrows.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-2673 size-large\" src=\"https:\/\/www.sqlskills.com\/blogs\/kimberly\/wp-content\/uploads\/2014\/10\/PlanEstimate_2014CE_withArrows-1024x891.jpg\" alt=\"Plan&amp;Estimate_2014CE_withArrows\" width=\"1024\" height=\"891\" srcset=\"https:\/\/www.sqlskills.com\/blogs\/kimberly\/wp-content\/uploads\/2014\/10\/PlanEstimate_2014CE_withArrows-1024x891.jpg 1024w, https:\/\/www.sqlskills.com\/blogs\/kimberly\/wp-content\/uploads\/2014\/10\/PlanEstimate_2014CE_withArrows-300x261.jpg 300w, https:\/\/www.sqlskills.com\/blogs\/kimberly\/wp-content\/uploads\/2014\/10\/PlanEstimate_2014CE_withArrows-900x783.jpg 900w, https:\/\/www.sqlskills.com\/blogs\/kimberly\/wp-content\/uploads\/2014\/10\/PlanEstimate_2014CE_withArrows.jpg 1152w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/a><\/p>\n<p>And, now we see the same plan &#8211; but, this time, the estimate is further off from the actual. And, another question might be &#8211; where did that number come from?<\/p>\n<p>In SQL Server 2014, regardless of multi-column statistics, the estimate for multiple conjunctive (AND) predicates is calculated using exponential back-off. The idea is that they take the highest selectivity first and then multiply that by the subsequent square roots of the next three less selective predicates. Specifically:<\/p>\n<pre style=\"padding-left: 30px;\"><strong>most-selective-predicate<\/strong> * <strong>sqrt(next most selective predicate)<\/strong> * <strong>sqrt(sqrt(next most selective predicate))<\/strong> *\u00a0<strong>sqrt(sqrt(sqrt(next most selective predicate)))<\/strong><\/pre>\n<p>In this case, they first need to calculate the selectivity of the two predicates supplied:<\/p>\n<p>To calculate the selectivity for <strong>[provider_no] = 434<\/strong>, use the histogram from the TestStat multi-column statistic (but, they don&#8217;t use the density vector of the combination). The histogram actually has a step for 434 and it shows 6625.247 rows in the EQ_ROWS column. The selectivity of this can be calculated as 6625.247 \/ 1600000 OR 0.00414077937.<\/p>\n<p>To calculate the selectivity for <strong>[category_no] = 10<\/strong>, use the histogram from the auto-created statistics on category_no (and, yes, this would have been created for this query if SQL Server hadn&#8217;t already created it for the other statement&#8217;s execution [which doesn&#8217;t entirely make sense because they didn&#8217;t use it. But, that&#8217;s another discussion for another day. And, if I&#8217;m being honest, as long as these get maintained properly, I&#8217;m ALL FOR AUTO CREATE STATS and I&#8217;d stand from the rooftops and scream it if it wouldn&#8217;t get me arrested&#8230; OK, sorry. I digress].<\/p>\n<p>Once again, we&#8217;re doing well with our histograms as there&#8217;s an actual step for 10 and it shows\u00a0179692.4 rows in the EQ_ROWS column. The selectivity of this can be calculated as\u00a0179692.4 \/ 1600000 OR 0.112307750.<\/p>\n<p>Now &#8211; to calculate our estimate&#8230; use the MOST selective predicate (0.00414077937) * the SQRT of the next most selective predicate\u00a0(0.112307750) * the number of rows:<\/p>\n<pre class=\"brush: sql; title: ; toolbar: true; wrap-lines: true; notranslate\" title=\"\">\r\nSELECT 0.00414077937 * sqrt(0.112307750) * 1600000;\r\nGO\r\n<\/pre>\n<p>For:<\/p>\n<pre class=\"brush: plain; gutter: false; title: ; toolbar: true; wrap-lines: true; notranslate\" title=\"\">\r\nNew CE Model Estimate\r\n----------------------\r\n2220.27585898223\r\n<\/pre>\n<p><strong>NOTE:<\/strong> How this is calculated may change in a later SP or CU so I can only vouch for 2014 RTM through CU3.<\/p>\n<p>Sure enough, this matches our showplan output.<\/p>\n<h2>What would the Legacy CE Model have done without multi-column statistics?<\/h2>\n<p>If we had not had our multi-column statistics then the Legacy CE Model would have just expected even distribution of providers across categories. To do this they&#8217;d simply multiply the selectivities (NOT backing off at all):<\/p>\n<pre class=\"brush: sql; title: ; toolbar: true; wrap-lines: true; notranslate\" title=\"\">\r\nSELECT 0.00414077937 * 0.112307750 * 1600000 AS [Legacy CE Model Estimate];\r\nGO<\/pre>\n<p>For:<\/p>\n<pre class=\"brush: plain; gutter: false; title: ; toolbar: true; wrap-lines: true; notranslate\" title=\"\">\r\nLegacy CE Model Estimate\r\n---------------------------------------\r\n744.06658286578800000000\r\n<\/pre>\n<p><strong>Tip:<\/strong> Drop the &#8216;TestStat&#8217; statistic and run the query again using TF 9481 to see this.<\/p>\n<h2>So, which CE is best?<\/h2>\n<p>This is where the good news and bad news comes in. There&#8217;s NO model that can deal with every type of data distribution possible. When data is evenly distributed across the different columns then the old model can produce a more accurate result:<\/p>\n<p style=\"padding-left: 30px;\">Legacy CE Model estimate: 744.07<\/p>\n<p style=\"padding-left: 30px;\">Multi-column statistics (just the AVERAGE of provider and category TOGETHER and across ALL values): 466.34<\/p>\n<p style=\"padding-left: 30px;\">New CE Model estimate: 2220.28<\/p>\n<p style=\"padding-left: 30px;\"><strong>ACTUAL: 656<\/strong><\/p>\n<p>The point &#8211; I could create another example where the New CE Model is the best. Here the Legacy CE is the best but the legacy CE doesn&#8217;t even use it because they rely on multi-column statistics (and therefore averages across all categories and providers). So, the irony is that they get further away with the generalized multi-column statistic. But, I could also come up with yet another example where the New CE Model produces the best result (and another where the multi-column statistic is best). In the end, it completely depends on THE DISTRIBUTION OF THE DATA.<\/p>\n<p>But, the really good news is that you have a lot of troubleshooting and control options here. My recommendation (you can read more about it in the post I linked to at the start of this post) is that you STAY using the Legacy CE Model and where estimates are OFF (or, where you&#8217;re troubleshooting a suspected\u00a0cardinality estimation problem), TRY the new CE using the QUERYTRACEON option. You can even try TF 4137 (this has been available since SQL Server 2008*) if you know that one value is a direct subset of the other (TF 4137 uses the MINIMUM selectivity of the predicates and does NOT perform a calculation).<\/p>\n<p>Above all &#8211; have fun!<br \/>\nkt<\/p>\n<p>* Thanks to <a href=\"http:\/\/blogs.msdn.com\/b\/blogdoezequiel\/\" class=\"broken_link\">Pedro<\/a> for reminding me to mention that TF 4137 has been around since SQL Server 2008. So, if you have predicates that are subsets of the others (WHERE city = &#8216;Chicago&#8217; AND state = &#8216;IL&#8217; AND country = &#8216;USA&#8217;) then you would NOT want EITHER model to estimate (even exponential back-off is going to be wrong here even though it will be higher than the old model). Here, Chicago is a subset of IL and IL a subset of USA. Using the MINIMUM selectivity of these predicates (which would be the selectivity of Chicago) would be best. However, if you had any other predicates in there &#8211; then, all bets are off. See &#8211; this is SUPER HARD! ;-) ;-)<\/p>\n","protected":false},"excerpt":{"rendered":"<p>After writing SQLskills procs to analyze data skew and create filtered statistics, I received a couple of emails asking me to further explain the sentence &#8220;This is also true for multi-column, column statistics (where you need to use MORE than just the first column) and hypothetical indexes created with auto pilot.&#8221; (NOTE: this refers to [&hellip;]<\/p>\n","protected":false},"author":7,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[91,72],"tags":[],"class_list":["post-2671","post","type-post","status-publish","format-standard","hentry","category-sql-server-2014","category-statistics"],"_links":{"self":[{"href":"https:\/\/www.sqlskills.com\/blogs\/kimberly\/wp-json\/wp\/v2\/posts\/2671","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.sqlskills.com\/blogs\/kimberly\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.sqlskills.com\/blogs\/kimberly\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.sqlskills.com\/blogs\/kimberly\/wp-json\/wp\/v2\/users\/7"}],"replies":[{"embeddable":true,"href":"https:\/\/www.sqlskills.com\/blogs\/kimberly\/wp-json\/wp\/v2\/comments?post=2671"}],"version-history":[{"count":0,"href":"https:\/\/www.sqlskills.com\/blogs\/kimberly\/wp-json\/wp\/v2\/posts\/2671\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.sqlskills.com\/blogs\/kimberly\/wp-json\/wp\/v2\/media?parent=2671"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.sqlskills.com\/blogs\/kimberly\/wp-json\/wp\/v2\/categories?post=2671"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.sqlskills.com\/blogs\/kimberly\/wp-json\/wp\/v2\/tags?post=2671"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}