<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>SQL Fool &#187; SQL 2008</title>
	<atom:link href="http://sqlfool.com/category/sql-2008/feed/" rel="self" type="application/rss+xml" />
	<link>http://sqlfool.com</link>
	<description>Adventures in SQL Tuning - a blog for the rest of us</description>
	<lastBuildDate>Fri, 16 Jul 2010 14:34:11 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Index Interrogation for SQL Server 2008</title>
		<link>http://sqlfool.com/2010/06/index-interrogation-for-sql-server-2008/</link>
		<comments>http://sqlfool.com/2010/06/index-interrogation-for-sql-server-2008/#comments</comments>
		<pubDate>Fri, 04 Jun 2010 19:55:17 +0000</pubDate>
		<dc:creator>Michelle Ufford</dc:creator>
				<category><![CDATA[Internals]]></category>
		<category><![CDATA[SQL 2008]]></category>
		<category><![CDATA[Syndication]]></category>
		<category><![CDATA[T-SQL Scripts]]></category>
		<category><![CDATA[indexes]]></category>
		<category><![CDATA[partitioning]]></category>
		<category><![CDATA[script]]></category>
		<category><![CDATA[tips]]></category>
		<category><![CDATA[TSQL]]></category>

		<guid isPermaLink="false">http://sqlfool.com/?p=1344</guid>
		<description><![CDATA[I had previously posted an index interrogation script for SQL Server 2005. I've updated that script for 2008; namely, it includes filtered index definitions. For anyone interested: DECLARE @objectID INT = OBJECT_ID&#40;'Sales.SalesOrderHeader'&#41;; &#160; WITH indexCTE&#40;partition_scheme_name , partition_function_name , data_space_id&#41; AS &#40; SELECT sps.name , spf.name , sps.data_space_id FROM sys.partition_schemes AS sps Join sys.partition_functions AS spf [...]]]></description>
			<content:encoded><![CDATA[<p>I had previously posted an index interrogation script for SQL Server 2005.  I've updated that script for 2008; namely, it includes filtered index definitions.  For anyone interested:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">DECLARE</span> @objectID <span style="color: #0000FF;">INT</span> <span style="color: #808080;">=</span> <span style="color: #FF00FF;">OBJECT_ID</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'Sales.SalesOrderHeader'</span><span style="color: #808080;">&#41;</span>;
&nbsp;
<span style="color: #0000FF;">WITH</span> indexCTE<span style="color: #808080;">&#40;</span>partition_scheme_name
            , partition_function_name
            , data_space_id<span style="color: #808080;">&#41;</span>
<span style="color: #0000FF;">AS</span> <span style="color: #808080;">&#40;</span>
    <span style="color: #0000FF;">SELECT</span> sps.<span style="color: #202020;">name</span>
        , spf.<span style="color: #202020;">name</span>
        , sps.<span style="color: #202020;">data_space_id</span>
    <span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">partition_schemes</span> <span style="color: #0000FF;">AS</span> sps
    Join sys.<span style="color: #202020;">partition_functions</span> <span style="color: #0000FF;">AS</span> spf
        <span style="color: #0000FF;">ON</span> sps.<span style="color: #202020;">function_id</span> <span style="color: #808080;">=</span> spf.<span style="color: #202020;">function_id</span>
<span style="color: #808080;">&#41;</span>
&nbsp;
<span style="color: #0000FF;">SELECT</span> st.<span style="color: #202020;">name</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'table_name'</span>
    , IsNull<span style="color: #808080;">&#40;</span>ix.<span style="color: #202020;">name</span>, <span style="color: #FF0000;">''</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'index_name'</span>
    , ix.<span style="color: #FF00FF;">OBJECT_ID</span>
    , ix.<span style="color: #202020;">index_id</span>
	, <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span>
        <span style="color: #0000FF;">CASE</span> <span style="color: #0000FF;">WHEN</span> ix.<span style="color: #202020;">index_id</span> <span style="color: #808080;">=</span> <span style="color: #000;">1</span> 
                <span style="color: #0000FF;">THEN</span> <span style="color: #FF0000;">'clustered'</span> 
            <span style="color: #0000FF;">WHEN</span> ix.<span style="color: #202020;">index_id</span> <span style="color: #808080;">=</span><span style="color: #000;">0</span>
                <span style="color: #0000FF;">THEN</span> <span style="color: #FF0000;">'heap'</span>
            <span style="color: #0000FF;">ELSE</span> <span style="color: #FF0000;">'nonclustered'</span> <span style="color: #0000FF;">END</span>
		<span style="color: #808080;">+</span> <span style="color: #0000FF;">CASE</span> <span style="color: #0000FF;">WHEN</span> ix.<span style="color: #202020;">ignore_dup_key</span> <span style="color: #808080;">&lt;&gt;</span> <span style="color: #000;">0</span> 
            <span style="color: #0000FF;">THEN</span> <span style="color: #FF0000;">', ignore duplicate keys'</span> 
                <span style="color: #0000FF;">ELSE</span> <span style="color: #FF0000;">''</span> <span style="color: #0000FF;">END</span>
		<span style="color: #808080;">+</span> <span style="color: #0000FF;">CASE</span> <span style="color: #0000FF;">WHEN</span> ix.<span style="color: #202020;">is_unique</span> <span style="color: #808080;">&lt;&gt;</span> <span style="color: #000;">0</span> 
            <span style="color: #0000FF;">THEN</span> <span style="color: #FF0000;">', unique'</span> 
                <span style="color: #0000FF;">ELSE</span> <span style="color: #FF0000;">''</span> <span style="color: #0000FF;">END</span>
		<span style="color: #808080;">+</span> <span style="color: #0000FF;">CASE</span> <span style="color: #0000FF;">WHEN</span> ix.<span style="color: #202020;">is_primary_key</span> <span style="color: #808080;">&lt;&gt;</span> <span style="color: #000;">0</span> 
            <span style="color: #0000FF;">THEN</span> <span style="color: #FF0000;">', primary key'</span> <span style="color: #0000FF;">ELSE</span> <span style="color: #FF0000;">''</span> <span style="color: #0000FF;">END</span> <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">210</span><span style="color: #808080;">&#41;</span>
        <span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'index_description'</span>
    , IsNull<span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">REPLACE</span><span style="color: #808080;">&#40;</span> <span style="color: #FF00FF;">REPLACE</span><span style="color: #808080;">&#40;</span> <span style="color: #FF00FF;">REPLACE</span><span style="color: #808080;">&#40;</span>
        <span style="color: #808080;">&#40;</span>   
            <span style="color: #0000FF;">SELECT</span> c.<span style="color: #202020;">name</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'columnName'</span>
            <span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">index_columns</span> <span style="color: #0000FF;">AS</span> sic
            Join sys.<span style="color: #202020;">columns</span> <span style="color: #0000FF;">AS</span> c 
                <span style="color: #0000FF;">ON</span> c.<span style="color: #202020;">column_id</span> <span style="color: #808080;">=</span> sic.<span style="color: #202020;">column_id</span> 
                And c.<span style="color: #FF00FF;">OBJECT_ID</span> <span style="color: #808080;">=</span> sic.<span style="color: #FF00FF;">OBJECT_ID</span>
            <span style="color: #0000FF;">WHERE</span> sic.<span style="color: #FF00FF;">OBJECT_ID</span> <span style="color: #808080;">=</span> ix.<span style="color: #FF00FF;">OBJECT_ID</span>
                And sic.<span style="color: #202020;">index_id</span> <span style="color: #808080;">=</span> ix.<span style="color: #202020;">index_id</span>
                And is_included_column <span style="color: #808080;">=</span> <span style="color: #000;">0</span>
            <span style="color: #0000FF;">ORDER</span> <span style="color: #0000FF;">BY</span> sic.<span style="color: #202020;">index_column_id</span>
            <span style="color: #0000FF;">FOR</span> XML Raw<span style="color: #808080;">&#41;</span>
            , <span style="color: #FF0000;">'&quot;/&gt;&lt;row columnName=&quot;'</span>, <span style="color: #FF0000;">', '</span><span style="color: #808080;">&#41;</span>
            , <span style="color: #FF0000;">'&lt;row columnName=&quot;'</span>, <span style="color: #FF0000;">''</span><span style="color: #808080;">&#41;</span>
            , <span style="color: #FF0000;">'&quot;/&gt;'</span>, <span style="color: #FF0000;">''</span><span style="color: #808080;">&#41;</span>, <span style="color: #FF0000;">''</span><span style="color: #808080;">&#41;</span>
        <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'indexed_columns'</span>
    , IsNull<span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">REPLACE</span><span style="color: #808080;">&#40;</span> <span style="color: #FF00FF;">REPLACE</span><span style="color: #808080;">&#40;</span> <span style="color: #FF00FF;">REPLACE</span><span style="color: #808080;">&#40;</span>
        <span style="color: #808080;">&#40;</span>   
            <span style="color: #0000FF;">SELECT</span> c.<span style="color: #202020;">name</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'columnName'</span>
            <span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">index_columns</span> <span style="color: #0000FF;">AS</span> sic
            Join sys.<span style="color: #202020;">columns</span> <span style="color: #0000FF;">AS</span> c 
                <span style="color: #0000FF;">ON</span> c.<span style="color: #202020;">column_id</span> <span style="color: #808080;">=</span> sic.<span style="color: #202020;">column_id</span> 
                And c.<span style="color: #FF00FF;">OBJECT_ID</span> <span style="color: #808080;">=</span> sic.<span style="color: #FF00FF;">OBJECT_ID</span>
            <span style="color: #0000FF;">WHERE</span> sic.<span style="color: #FF00FF;">OBJECT_ID</span> <span style="color: #808080;">=</span> ix.<span style="color: #FF00FF;">OBJECT_ID</span>
                And sic.<span style="color: #202020;">index_id</span> <span style="color: #808080;">=</span> ix.<span style="color: #202020;">index_id</span>
                And is_included_column <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
            <span style="color: #0000FF;">ORDER</span> <span style="color: #0000FF;">BY</span> sic.<span style="color: #202020;">index_column_id</span>
            <span style="color: #0000FF;">FOR</span> XML Raw<span style="color: #808080;">&#41;</span>
            , <span style="color: #FF0000;">'&quot;/&gt;&lt;row columnName=&quot;'</span>, <span style="color: #FF0000;">', '</span><span style="color: #808080;">&#41;</span>
            , <span style="color: #FF0000;">'&lt;row columnName=&quot;'</span>, <span style="color: #FF0000;">''</span><span style="color: #808080;">&#41;</span>
            , <span style="color: #FF0000;">'&quot;/&gt;'</span>, <span style="color: #FF0000;">''</span><span style="color: #808080;">&#41;</span>, <span style="color: #FF0000;">''</span><span style="color: #808080;">&#41;</span>
        <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'included_columns'</span>
    , ix.<span style="color: #202020;">filter_definition</span>
    , IsNull<span style="color: #808080;">&#40;</span>cte.<span style="color: #202020;">partition_scheme_name</span>, <span style="color: #FF0000;">''</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'partition_scheme_name'</span>
    , <span style="color: #FF00FF;">COUNT</span><span style="color: #808080;">&#40;</span>partition_number<span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'partition_count'</span>
    , <span style="color: #FF00FF;">SUM</span><span style="color: #808080;">&#40;</span><span style="color: #0000FF;">ROWS</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'row_count'</span>
<span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">indexes</span> <span style="color: #0000FF;">AS</span> ix
Join sys.<span style="color: #202020;">partitions</span> <span style="color: #0000FF;">AS</span> sp
    <span style="color: #0000FF;">ON</span> ix.<span style="color: #FF00FF;">OBJECT_ID</span> <span style="color: #808080;">=</span> sp.<span style="color: #FF00FF;">OBJECT_ID</span>
    And ix.<span style="color: #202020;">index_id</span> <span style="color: #808080;">=</span> sp.<span style="color: #202020;">index_id</span>
Join sys.<span style="color: #202020;">tables</span> <span style="color: #0000FF;">AS</span> st
    <span style="color: #0000FF;">ON</span> ix.<span style="color: #FF00FF;">OBJECT_ID</span> <span style="color: #808080;">=</span> st.<span style="color: #FF00FF;">OBJECT_ID</span>
<span style="color: #0000FF;">LEFT</span> Join indexCTE <span style="color: #0000FF;">AS</span> cte
    <span style="color: #0000FF;">ON</span> ix.<span style="color: #202020;">data_space_id</span> <span style="color: #808080;">=</span> cte.<span style="color: #202020;">data_space_id</span>
<span style="color: #0000FF;">WHERE</span> ix.<span style="color: #FF00FF;">OBJECT_ID</span> <span style="color: #808080;">=</span> IsNull<span style="color: #808080;">&#40;</span>@objectID, ix.<span style="color: #FF00FF;">OBJECT_ID</span><span style="color: #808080;">&#41;</span>
<span style="color: #0000FF;">GROUP</span> <span style="color: #0000FF;">BY</span> st.<span style="color: #202020;">name</span>
    , IsNull<span style="color: #808080;">&#40;</span>ix.<span style="color: #202020;">name</span>, <span style="color: #FF0000;">''</span><span style="color: #808080;">&#41;</span>
    , ix.<span style="color: #FF00FF;">OBJECT_ID</span>
    , ix.<span style="color: #202020;">index_id</span>
	, <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span>
        <span style="color: #0000FF;">CASE</span> <span style="color: #0000FF;">WHEN</span> ix.<span style="color: #202020;">index_id</span> <span style="color: #808080;">=</span> <span style="color: #000;">1</span> 
                <span style="color: #0000FF;">THEN</span> <span style="color: #FF0000;">'clustered'</span> 
            <span style="color: #0000FF;">WHEN</span> ix.<span style="color: #202020;">index_id</span> <span style="color: #808080;">=</span><span style="color: #000;">0</span>
                <span style="color: #0000FF;">THEN</span> <span style="color: #FF0000;">'heap'</span>
            <span style="color: #0000FF;">ELSE</span> <span style="color: #FF0000;">'nonclustered'</span> <span style="color: #0000FF;">END</span>
		<span style="color: #808080;">+</span> <span style="color: #0000FF;">CASE</span> <span style="color: #0000FF;">WHEN</span> ix.<span style="color: #202020;">ignore_dup_key</span> <span style="color: #808080;">&lt;&gt;</span> <span style="color: #000;">0</span> 
            <span style="color: #0000FF;">THEN</span> <span style="color: #FF0000;">', ignore duplicate keys'</span> 
                <span style="color: #0000FF;">ELSE</span> <span style="color: #FF0000;">''</span> <span style="color: #0000FF;">END</span>
		<span style="color: #808080;">+</span> <span style="color: #0000FF;">CASE</span> <span style="color: #0000FF;">WHEN</span> ix.<span style="color: #202020;">is_unique</span> <span style="color: #808080;">&lt;&gt;</span> <span style="color: #000;">0</span> 
            <span style="color: #0000FF;">THEN</span> <span style="color: #FF0000;">', unique'</span> 
                <span style="color: #0000FF;">ELSE</span> <span style="color: #FF0000;">''</span> <span style="color: #0000FF;">END</span>
		<span style="color: #808080;">+</span> <span style="color: #0000FF;">CASE</span> <span style="color: #0000FF;">WHEN</span> ix.<span style="color: #202020;">is_primary_key</span> <span style="color: #808080;">&lt;&gt;</span> <span style="color: #000;">0</span> 
            <span style="color: #0000FF;">THEN</span> <span style="color: #FF0000;">', primary key'</span> <span style="color: #0000FF;">ELSE</span> <span style="color: #FF0000;">''</span> <span style="color: #0000FF;">END</span> <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">210</span><span style="color: #808080;">&#41;</span>
        <span style="color: #808080;">&#41;</span>
    , ix.<span style="color: #202020;">filter_definition</span>
    , IsNull<span style="color: #808080;">&#40;</span>cte.<span style="color: #202020;">partition_scheme_name</span>, <span style="color: #FF0000;">''</span><span style="color: #808080;">&#41;</span>
    , IsNull<span style="color: #808080;">&#40;</span>cte.<span style="color: #202020;">partition_function_name</span>, <span style="color: #FF0000;">''</span><span style="color: #808080;">&#41;</span>
<span style="color: #0000FF;">ORDER</span> <span style="color: #0000FF;">BY</span> table_name
    , index_id;</pre></div></div>

<p>You may need to create some indexes to see this in AdventureWorks:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">NONCLUSTERED</span> <span style="color: #0000FF;">INDEX</span> IX_Sales_SalesOrderHeader_filtered_2005
    <span style="color: #0000FF;">ON</span> Sales.<span style="color: #202020;">SalesOrderHeader</span><span style="color: #808080;">&#40;</span>AccountNumber<span style="color: #808080;">&#41;</span>
    Include <span style="color: #808080;">&#40;</span>CustomerID, SalesPersonID<span style="color: #808080;">&#41;</span>
    <span style="color: #0000FF;">WHERE</span> OrderDate <span style="color: #808080;">&gt;=</span> <span style="color: #FF0000;">'2005-01-01'</span>
        And OrderDate <span style="color: #808080;">&lt;</span> <span style="color: #FF0000;">'2006-01-01'</span>;</pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">table_name           index_name                               object_id   index_id    index_description                   indexed_columns      included_columns               filter_definition                                            partition_scheme_name partition_count row_count
-------------------- ---------------------------------------- ----------- ----------- ----------------------------------- -------------------- ------------------------------ ------------------------------------------------------------ --------------------- --------------- --------------------
SalesOrderHeader     PK_SalesOrderHeader_SalesOrderID         1010102639  1           clustered, unique, primary key      SalesOrderID                                        NULL                                                                               1               31465
SalesOrderHeader     AK_SalesOrderHeader_rowguid              1010102639  2           nonclustered, unique                rowguid                                             NULL                                                                               1               31465
SalesOrderHeader     AK_SalesOrderHeader_SalesOrderNumber     1010102639  3           nonclustered, unique                SalesOrderNumber                                    NULL                                                                               1               31465
SalesOrderHeader     IX_SalesOrderHeader_CustomerID           1010102639  5           nonclustered                        CustomerID                                          NULL                                                                               1               31465
SalesOrderHeader     IX_SalesOrderHeader_SalesPersonID        1010102639  6           nonclustered                        SalesPersonID                                       NULL                                                                               1               31465
SalesOrderHeader     IX_Sales_SalesOrderHeader_filtered_2005  1010102639  13          nonclustered                        AccountNumber        CustomerID, SalesPersonID      ([OrderDate]&gt;='2005-01-01' AND [OrderDate]&lt;'2006-01-01')                           1               1379</pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://sqlfool.com/2010/06/index-interrogation-for-sql-server-2008/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Filtered Indexes Work-Around</title>
		<link>http://sqlfool.com/2010/02/filtered-indexes-work-around/</link>
		<comments>http://sqlfool.com/2010/02/filtered-indexes-work-around/#comments</comments>
		<pubDate>Mon, 01 Feb 2010 16:00:14 +0000</pubDate>
		<dc:creator>Michelle Ufford</dc:creator>
				<category><![CDATA[Performance & Tuning]]></category>
		<category><![CDATA[SQL 2008]]></category>
		<category><![CDATA[SQL Tips]]></category>
		<category><![CDATA[Syndication]]></category>
		<category><![CDATA[2008]]></category>
		<category><![CDATA[filtered indexes]]></category>
		<category><![CDATA[performance]]></category>

		<guid isPermaLink="false">http://sqlfool.com/?p=1307</guid>
		<description><![CDATA[Recently, I needed to create a stored procedure that queried a rather large table. The table has a filtered index on a date column, and it covers the query. However, the Query Optimizer was not using the index, which was increasing the execution time (not to mention IO!) by at least 10x. This wasn't the [...]]]></description>
			<content:encoded><![CDATA[<p>Recently, I needed to create a stored procedure that queried a rather large table.  The table has a filtered index on a date column, and it covers the query.  However, the Query Optimizer was not using the index, which was increasing the execution time (not to mention IO!) by at least 10x.  This wasn't the first time I've had the Optimizer fail to use a filtered index.  Normally when this happens, I use a table hint to force the filtered index -- after I verify that it is indeed faster, of course.  However, since this was a stored procedure, I was receiving the following error message whenever I tried to execute the proc:</p>
<p><span style="color: #ff0000;">Query processor could not produce a query plan because of the hints defined in this query. Resubmit the query without specifying any hints and without using SET FORCEPLAN.</span></p>
<p>SQL Server would not allow me to execute the stored procedure using the filtered index hint.  If I removed the hint, it executed, but it used a different, non-covering and far more expensive index.  For those of you not familiar with this issue, allow me to illustrate the problem.</p>
<p>First, create a table to play with and populate it with some bogus data:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">TABLE</span> dbo.<span style="color: #202020;">filteredIndexTest</span>
<span style="color: #808080;">&#40;</span>
      myID   <span style="color: #0000FF;">INT</span> <span style="color: #0000FF;">IDENTITY</span><span style="color: #808080;">&#40;</span><span style="color: #000;">1</span>,<span style="color: #000;">3</span><span style="color: #808080;">&#41;</span>
    , myDate <span style="color: #0000FF;">SMALLDATETIME</span> 
    , myData <span style="color: #0000FF;">CHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">100</span><span style="color: #808080;">&#41;</span>
&nbsp;
    <span style="color: #0000FF;">CONSTRAINT</span> PK_filteredIndexTest
        <span style="color: #0000FF;">PRIMARY</span> <span style="color: #0000FF;">KEY</span> <span style="color: #0000FF;">CLUSTERED</span><span style="color: #808080;">&#40;</span>myID<span style="color: #808080;">&#41;</span>
<span style="color: #808080;">&#41;</span>;
&nbsp;
<span style="color: #0000FF;">SET</span> <span style="color: #0000FF;">NOCOUNT</span> <span style="color: #0000FF;">ON</span>;
<span style="color: #0000FF;">DECLARE</span> @<span style="color: #0000FF;">DATE</span> <span style="color: #0000FF;">SMALLDATETIME</span> <span style="color: #808080;">=</span> <span style="color: #FF0000;">'2010-01-01'</span>;
&nbsp;
<span style="color: #0000FF;">WHILE</span> @<span style="color: #0000FF;">DATE</span> <span style="color: #808080;">&lt;</span> <span style="color: #FF0000;">'2010-02-01'</span>
<span style="color: #0000FF;">BEGIN</span>
&nbsp;
    <span style="color: #0000FF;">INSERT</span> <span style="color: #0000FF;">INTO</span> dbo.<span style="color: #202020;">filteredIndexTest</span>
    <span style="color: #808080;">&#40;</span>
          myDate
        , myData
    <span style="color: #808080;">&#41;</span>
    <span style="color: #0000FF;">SELECT</span> @<span style="color: #0000FF;">DATE</span>
        , <span style="color: #FF0000;">'Date: '</span> <span style="color: #808080;">+</span> <span style="color: #0000FF;">CONVERT</span><span style="color: #808080;">&#40;</span><span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">20</span><span style="color: #808080;">&#41;</span>, @<span style="color: #0000FF;">DATE</span>, <span style="color: #000;">102</span><span style="color: #808080;">&#41;</span>;
&nbsp;
    <span style="color: #0000FF;">SET</span> @<span style="color: #0000FF;">DATE</span> <span style="color: #808080;">=</span> <span style="color: #FF00FF;">DATEADD</span><span style="color: #808080;">&#40;</span><span style="color: #0000FF;">MINUTE</span>, <span style="color: #000;">1</span>, @<span style="color: #0000FF;">DATE</span><span style="color: #808080;">&#41;</span>;
&nbsp;
<span style="color: #0000FF;">END</span>;
&nbsp;
<span style="color: #0000FF;">SELECT</span> <span style="color: #FF00FF;">COUNT</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">*</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">FROM</span> dbo.<span style="color: #202020;">filteredIndexTest</span>;</pre></div></div>

<p>It looks like this will generate 44,640 rows of test data... plenty enough for our purposes.  Now, let's create our filtered index and write a query that will use it:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">NONCLUSTERED</span> <span style="color: #0000FF;">INDEX</span> IX_filteredIndexTest_1
    <span style="color: #0000FF;">ON</span> dbo.<span style="color: #202020;">filteredIndexTest</span><span style="color: #808080;">&#40;</span>myDate<span style="color: #808080;">&#41;</span>
    Include <span style="color: #808080;">&#40;</span>myData<span style="color: #808080;">&#41;</span>
    <span style="color: #0000FF;">WHERE</span> myDate <span style="color: #808080;">&gt;=</span> <span style="color: #FF0000;">'2010-01-27'</span>;
&nbsp;
<span style="color: #0000FF;">SELECT</span> <span style="color: #0000FF;">DISTINCT</span> myData
<span style="color: #0000FF;">FROM</span> dbo.<span style="color: #202020;">filteredIndexTest</span>
<span style="color: #0000FF;">WHERE</span> myDate <span style="color: #808080;">&gt;=</span> <span style="color: #FF0000;">'2010-01-28'</span>;</pre></div></div>

<p>If you look at the execution plan for this query, you'll notice that the Optimizer is using the filtered index.  Perfect!  Now let's parameterize it.</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">DECLARE</span> @myDate1 <span style="color: #0000FF;">SMALLDATETIME</span> <span style="color: #808080;">=</span> <span style="color: #FF0000;">'2010-01-28'</span>;
&nbsp;
<span style="color: #0000FF;">SELECT</span> <span style="color: #0000FF;">DISTINCT</span> myData
<span style="color: #0000FF;">FROM</span> dbo.<span style="color: #202020;">filteredIndexTest</span>
<span style="color: #0000FF;">WHERE</span> myDate <span style="color: #808080;">&gt;=</span> @myDate1;</pre></div></div>

<p>Uh oh.  Looking at the execution plan, we see that SQL Server is no longer using the filtered index.  Instead, it's scanning the clustered index!  Why is this?  There's actually a good explanation for it.  The reason is that I could, in theory, pass a date to my parameter that fell outside of the filtered date range.  If that's the case, then SQL Server could not utilize the filtered index.  Personally, I think it's a bug and SQL Server should identify whether or not a filtered index could be used based on the actual value submitted, but... that's a whole other blog post.  <img src='http://sqlfool.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />   </p>
<p>So what can we do?  Well, dynamic SQL may be able to help us out in this case.  Let's give it a go.  First, let's try parameterized dynamic SQL.</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">DECLARE</span> @mySQL1 <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">2000</span><span style="color: #808080;">&#41;</span>
    , @myParam <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">2000</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">=</span> <span style="color: #FF0000;">'@p_myDate2 smalldatetime'</span>
    , @myDate2 <span style="color: #0000FF;">SMALLDATETIME</span> <span style="color: #808080;">=</span> <span style="color: #FF0000;">'2010-01-28'</span>;
&nbsp;
<span style="color: #0000FF;">SET</span> @mySQL1 <span style="color: #808080;">=</span> <span style="color: #FF0000;">'Select Distinct myData
              From dbo.filteredIndexTest
              Where myDate &gt;= @p_myDate2'</span>;
&nbsp;
<span style="color: #0000FF;">EXECUTE</span> <span style="color: #AF0000;">SP_EXECUTESQL</span> @mySQL1, @myParam, @p_myDate2 <span style="color: #808080;">=</span> @myDate2;</pre></div></div>

<p>Looking at the execution plan, we see we're still scanning on the clustered index.  This is because the parameterized dynamic SQL resolves to be the exact same query as the one above it.  Let's try unparameterized SQL instead:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">DECLARE</span> @mySQL2 <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">2000</span><span style="color: #808080;">&#41;</span>
    , @myDate3 <span style="color: #0000FF;">SMALLDATETIME</span> <span style="color: #808080;">=</span> <span style="color: #FF0000;">'2010-01-28'</span>;
&nbsp;
<span style="color: #0000FF;">SET</span> @mySQL2 <span style="color: #808080;">=</span> <span style="color: #FF0000;">'Select Distinct myData
              From dbo.filteredIndexTest
              Where myDate &gt;= '</span><span style="color: #FF0000;">''</span> <span style="color: #808080;">+</span> <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span>@myDate3 <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">20</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">+</span> <span style="color: #FF0000;">''</span><span style="color: #FF0000;">''</span>;
&nbsp;
<span style="color: #0000FF;">EXECUTE</span> <span style="color: #AF0000;">SP_EXECUTESQL</span> @mySQL2;
&nbsp;
<span style="color: #008080;">-- Drop Table dbo.filteredIndexTest;</span></pre></div></div>

<p>Voila!  We have a seek on our filtered index.  Why?  Because the statement resolves to be identical to our first query, where we hard-coded the date value in the WHERE clause.</p>
<p>Now, I want to stress this fact: you should always, ALWAYS use parameterized dynamic SQL whenever possible.  Not only is it safer, but it's also faster, because it can reuse cached plans.  But sometimes you just cannot accomplish the same tasks with it.  This is one of those times.  If you do end up needing to use unparameterized dynamic SQL as a work-around, please make sure you're validating your input, especially if you're interfacing with any sort of external source.</p>
<p>There's an even easier work-around for this problem that <a href="http://twitter.com/CrappyCodingGuy ">Dave</a> (<a href="http://www.crappycoding.com" target="_blank">http://www.crappycoding.com</a>) shared with me: <a href="http://msdn.microsoft.com/en-us/library/ms181714.aspx" target="_blank">recompile</a>.</p>
<p>Adding "Option (Recompile)" to the end of your statements will force the Optimizer to re-evaluate which index will best meet the needs of your query every time the statement is executed.  More importantly, it evaluates the plan based on the actual values passed to the parameter... just like in our hard-coded and dynamic SQL examples.  Let's see it in action:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">DECLARE</span> @myDate4 <span style="color: #0000FF;">SMALLDATETIME</span> <span style="color: #808080;">=</span> <span style="color: #FF0000;">'2010-01-28'</span>;
&nbsp;
<span style="color: #0000FF;">SELECT</span> <span style="color: #0000FF;">DISTINCT</span> myData
<span style="color: #0000FF;">FROM</span> dbo.<span style="color: #202020;">filteredIndexTest</span> 
<span style="color: #0000FF;">WHERE</span> myDate <span style="color: #808080;">&gt;=</span> @myDate4
<span style="color: #0000FF;">OPTION</span> <span style="color: #808080;">&#40;</span>RECOMPILE<span style="color: #808080;">&#41;</span>;
&nbsp;
<span style="color: #0000FF;">DECLARE</span> @myDate5 <span style="color: #0000FF;">SMALLDATETIME</span> <span style="color: #808080;">=</span> <span style="color: #FF0000;">'2010-01-20'</span>;
&nbsp;
<span style="color: #0000FF;">SELECT</span> <span style="color: #0000FF;">DISTINCT</span> myData
<span style="color: #0000FF;">FROM</span> dbo.<span style="color: #202020;">filteredIndexTest</span> 
<span style="color: #0000FF;">WHERE</span> myDate <span style="color: #808080;">&gt;=</span> @myDate5
<span style="color: #0000FF;">OPTION</span> <span style="color: #808080;">&#40;</span>RECOMPILE<span style="color: #808080;">&#41;</span>;</pre></div></div>

<p>If we look at the execution plans for the 2 queries above, we see that the first query seeks on the filtered index, and the second query scans on the clustered index.  This is because the second query cannot be satisfied with the filtered index because we initially limited our index to dates greater than or equal to 1/27/2010.  </p>
<p>There are, of course, trade-offs associated with each approach, so use whichever one best meets your needs.  Do you have another work-around for this issue?  If so, please let me know.  <img src='http://sqlfool.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Update:  </p>
<p>Alex Kuznetsov (<a href="http://www.simple-talk.com/author/alex-kuznetsov/">http://www.simple-talk.com/author/alex-kuznetsov/</a>) shared this method too:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">DECLARE</span> @myDate1 <span style="color: #0000FF;">SMALLDATETIME</span> <span style="color: #808080;">=</span> <span style="color: #FF0000;">'2010-01-28'</span>;
&nbsp;
<span style="color: #0000FF;">SELECT</span> <span style="color: #0000FF;">DISTINCT</span> myData
<span style="color: #0000FF;">FROM</span> dbo.<span style="color: #202020;">filteredIndexTest</span>
<span style="color: #0000FF;">WHERE</span> myDate <span style="color: #808080;">=</span> @myDate1
<span style="color: #808080;">AND</span> myDate <span style="color: #808080;">&gt;=</span> <span style="color: #FF0000;">'2010-01-27'</span>;</pre></div></div>

<p>Like the other examples, this will result in an index seek on the filtered index.  Basically, by explicitly declaring the start date of your filter, you're letting the Optimizer know that the filtered index can satisfy the request, regardless of the parameter value passed.  Thanks for the tip, Alex!  <img src='http://sqlfool.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://sqlfool.com/2010/02/filtered-indexes-work-around/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Index Defrag Script Updates &#8211; Beta Testers Needed</title>
		<link>http://sqlfool.com/2010/01/index-defrag-script-updates-beta-testers-needed/</link>
		<comments>http://sqlfool.com/2010/01/index-defrag-script-updates-beta-testers-needed/#comments</comments>
		<pubDate>Tue, 26 Jan 2010 21:15:37 +0000</pubDate>
		<dc:creator>Michelle Ufford</dc:creator>
				<category><![CDATA[Miscellaneous]]></category>
		<category><![CDATA[Performance & Tuning]]></category>
		<category><![CDATA[SQL 2008]]></category>
		<category><![CDATA[Syndication]]></category>
		<category><![CDATA[T-SQL Scripts]]></category>
		<category><![CDATA[defrag]]></category>
		<category><![CDATA[defragment]]></category>
		<category><![CDATA[indexes]]></category>
		<category><![CDATA[script]]></category>

		<guid isPermaLink="false">http://sqlfool.com/?p=1298</guid>
		<description><![CDATA[Update: Wow! I've received a ton of responses to my request for beta testers. Thank you all! The SQL Community is really amazing. I'll hopefully have the new version online in just a few days. Over the last few months, I've received many great comments and suggestions regarding my Index Defrag Script v3.0. I've just [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Update:  </strong>Wow!  I've received a ton of responses to my request for beta testers.  Thank you all!  The SQL Community is really amazing.  I'll hopefully have the new version online in just a few days.  <img src='http://sqlfool.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Over the last few months, I've received many great comments and suggestions regarding my Index Defrag Script v3.0.  I've just recently had time to implement most of these suggestions, plus some other things that I thought would be useful.  <img src='http://sqlfool.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  </p>
<p>Here's some of what you can look forward to shortly:</p>
<ul>
<li>Probably the single most requested feature, the new version of the script allows you to set a time limit for index defrags.</li>
<li>There's now a static table for managing the status of index defrags.  This way, when your time limit is reached, you can pick up where you left off the next day, without the need to rescan indexes.</li>
<li>There's now an option to prioritize defrags by range scan counts, fragmentation level, or page counts.</li>
<li>For those using partitioning, there is now an option to exclude the right-most populated partition from defrags (in theory, the one you're writing to in a sliding-window scenario).</li>
<li>Options such as page count limits and SORT_IN_TEMPDB are now parameterized.</li>
<li>I've enhanced error logging.</li>
<li>... and more!</li>
</ul>
<p>Right now, I'm looking for a few folks who are willing to beta test the script.  If you're interested, please send me an e-mail at <em>michelle </em>at <em>sqlfool </em>dot <em>com</em> with the editions of SQL Server you can test this on (i.e. 2005 Standard, 2008 Enterprise, etc.).  </p>
<p>Thank you!  <img src='http://sqlfool.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://sqlfool.com/2010/01/index-defrag-script-updates-beta-testers-needed/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Partitioning Tricks</title>
		<link>http://sqlfool.com/2009/10/partitioning-tricks/</link>
		<comments>http://sqlfool.com/2009/10/partitioning-tricks/#comments</comments>
		<pubDate>Fri, 09 Oct 2009 19:12:35 +0000</pubDate>
		<dc:creator>Michelle Ufford</dc:creator>
				<category><![CDATA[Miscellaneous]]></category>
		<category><![CDATA[Performance & Tuning]]></category>
		<category><![CDATA[SQL 2008]]></category>
		<category><![CDATA[SQL Tips]]></category>
		<category><![CDATA[Syndication]]></category>
		<category><![CDATA[2008]]></category>
		<category><![CDATA[compression]]></category>
		<category><![CDATA[partitioning]]></category>
		<category><![CDATA[performance]]></category>

		<guid isPermaLink="false">http://sqlfool.com/?p=1195</guid>
		<description><![CDATA[For those of you who are using partitioning, or who are considering using partitioning, allow me to share some tips with you. Easy Partition Staging Tables Switching partitions (or more specifically, hobts) in and out of a partitioned table requires the use of a staging table. The staging table has very specific requirements: it must [...]]]></description>
			<content:encoded><![CDATA[<p>For those of you who are using partitioning, or who are considering using partitioning, allow me to share some tips with you.</p>
<p><strong>Easy Partition Staging Tables</strong></p>
<p>Switching partitions (or more specifically, hobts) in and out of a partitioned table requires the use of a staging table.  The staging table has very specific requirements: it must be completely identical to the partitioned table, including indexing structures, and it must have a check constraint that limits data to the partitioning range.  Thanks to my co-worker Jeff, I've recently started using the <a href="http://sqlpartitionmgmt.codeplex.com/" target="_blank">SQL Server Partition Management</a> tool on CodePlex.  I haven't used the automatic partition switching feature -- frankly, using any sort of data modification tool in a production environment makes me nervous -- but I've been using the scripting option to create staging tables in my development environment, which I then copy to production for use.  It's nothing you can't do yourself, but it does make the whole process easy and painless, plus it saves you from annoying typos.  But be careful when using this tool to just create the table and check constraints automatically, because you may need to...</p>
<p><strong>Add Check Constraints After Loading Data</strong></p>
<p>Most of the time, I add the check constraint when I create the staging table, then I load data and perform the partition switch.  However, for some reason, I was receiving the following error:</p>
<p><span style="color: #ff0000;">.Net SqlClient Data Provider: Msg 4972, Level 16, State 1, Line 1<br />
ALTER TABLE SWITCH statement failed. Check constraints or partition function of source table 'myStagingTable' allows values that are not allowed by check constraints or partition function on target table 'myDestinationTable'.</span></p>
<p>This drove me crazy.  I confirmed my check constraints were correct, that I had the correct partition number, and that all schema and indexes matched identically.  After about 30 minutes of this, I decided to drop and recreate the constraint.  For some reason, it fixed the issue.  Repeat tests produced the same results:  the check constraint needed to be added *after* data was loaded.  This error is occurring on a SQL Server 2008 SP1 box; to be honest, I'm not sure what's causing the error, so if you know, please leave me a comment.  But I figured I'd share so that anyone else running into this issue can hopefully save some time and headache.  <img src='http://sqlfool.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><strong>Replicating Into Partitioned and Non-Partitioned Tables</strong></p>
<p>Recently, we needed to replicate a non-partitioned table to two different destinations.  We wanted to use partitioning for Server A, which has 2008 Enterprise; Server B, which is on 2005 Standard, could not take advantage of partitioning.  The solution was really easy:  create a pre-snapshot and post-snapshot script for the publication, then modify to handle each server group differently.  Using pseudo-code, it looked something like this:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #008080;">/* Identify which servers get the partitioned version */</span>
<span style="color: #0000FF;">IF</span> <span style="color: #FF00FF;">@@SERVERNAME</span> In <span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'yourServerNameList'</span><span style="color: #808080;">&#41;</span> 
<span style="color: #0000FF;">BEGIN</span>
&nbsp;
    <span style="color: #008080;">/* Create your partitioning scheme if necessary */</span>
    <span style="color: #0000FF;">IF</span> Not Exists<span style="color: #808080;">&#40;</span><span style="color: #0000FF;">SELECT</span> <span style="color: #808080;">*</span> <span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">partition_schemes</span> <span style="color: #0000FF;">WHERE</span> name <span style="color: #808080;">=</span> <span style="color: #FF0000;">'InsertPartitionScheme'</span><span style="color: #808080;">&#41;</span>
        <span style="color: #0000FF;">CREATE</span> PARTITION SCHEME InsertPartitionScheme 
            <span style="color: #0000FF;">AS</span> PARTITION InsertPartitionFunction <span style="color: #808080;">ALL</span> <span style="color: #0000FF;">TO</span> <span style="color: #808080;">&#40;</span><span style="color: #808080;">&#91;</span><span style="color: #0000FF;">PRIMARY</span><span style="color: #808080;">&#93;</span><span style="color: #808080;">&#41;</span>;    
&nbsp;
    <span style="color: #008080;">/* Create your partitioning function if necessary */</span>
    <span style="color: #0000FF;">IF</span> Not Exists<span style="color: #808080;">&#40;</span><span style="color: #0000FF;">SELECT</span> <span style="color: #808080;">*</span> <span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">partition_functions</span> <span style="color: #0000FF;">WHERE</span> name <span style="color: #808080;">=</span> <span style="color: #FF0000;">'InsertPartitionFunction'</span><span style="color: #808080;">&#41;</span>
        <span style="color: #0000FF;">CREATE</span> PARTITION <span style="color: #0000FF;">FUNCTION</span> InsertPartitionFunction <span style="color: #808080;">&#40;</span><span style="color: #0000FF;">SMALLDATETIME</span><span style="color: #808080;">&#41;</span> 
            <span style="color: #0000FF;">AS</span> RANGE <span style="color: #0000FF;">RIGHT</span> <span style="color: #0000FF;">FOR</span> <span style="color: #0000FF;">VALUES</span> <span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'insertValues'</span><span style="color: #808080;">&#41;</span>;    
&nbsp;
    <span style="color: #008080;">/* Create a partitioned version of your table */</span>
    <span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">TABLE</span> <span style="color: #808080;">&#91;</span>dbo<span style="color: #808080;">&#93;</span>.<span style="color: #808080;">&#91;</span>yourTableName<span style="color: #808080;">&#93;</span> <span style="color: #808080;">&#40;</span>
	    <span style="color: #808080;">&#91;</span>yourTableSchema<span style="color: #808080;">&#93;</span>
    <span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">ON</span> InsertPartitionScheme<span style="color: #808080;">&#40;</span><span style="color: #808080;">&#91;</span>partitioningKey<span style="color: #808080;">&#93;</span><span style="color: #808080;">&#41;</span>;
&nbsp;
<span style="color: #0000FF;">END</span>
<span style="color: #0000FF;">ELSE</span>
<span style="color: #0000FF;">BEGIN</span>
&nbsp;
    <span style="color: #008080;">/* Create a non-partitioned version of your table */</span>
    <span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">TABLE</span> <span style="color: #808080;">&#91;</span>dbo<span style="color: #808080;">&#93;</span>.<span style="color: #808080;">&#91;</span>yourTableName<span style="color: #808080;">&#93;</span> <span style="color: #808080;">&#40;</span>
	    <span style="color: #808080;">&#91;</span>yourTableSchema<span style="color: #808080;">&#93;</span>
    <span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">ON</span> <span style="color: #808080;">&#91;</span><span style="color: #0000FF;">PRIMARY</span><span style="color: #808080;">&#93;</span>;
&nbsp;
<span style="color: #0000FF;">END</span></pre></div></div>

<p>You could also use an edition check instead of a server name check, if you prefer.  The post-snapshot script basically looked the same, except you create partitioned indexes instead.</p>
<p><strong>Compress Old Partitions</strong></p>
<p>Did you know you can set different compression levels for individual partitions?  It's true!  I've just completed doing this on our largest partitioned table.  Here's how:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #008080;">/* Apply compression to your partitioned table */</span>
<span style="color: #0000FF;">ALTER</span> <span style="color: #0000FF;">TABLE</span> dbo.<span style="color: #202020;">yourTableName</span>
Rebuild Partition <span style="color: #808080;">=</span> All
<span style="color: #0000FF;">WITH</span> 
<span style="color: #808080;">&#40;</span>
      Data_Compression <span style="color: #808080;">=</span> Page <span style="color: #0000FF;">ON</span> Partitions<span style="color: #808080;">&#40;</span><span style="color: #000;">1</span> <span style="color: #0000FF;">TO</span> <span style="color: #000;">9</span><span style="color: #808080;">&#41;</span>
    , Data_Compression <span style="color: #808080;">=</span> <span style="color: #0000FF;">ROW</span>  <span style="color: #0000FF;">ON</span> Partitions<span style="color: #808080;">&#40;</span><span style="color: #000;">10</span> <span style="color: #0000FF;">TO</span> <span style="color: #000;">11</span><span style="color: #808080;">&#41;</span> 
    , Data_Compression <span style="color: #808080;">=</span> <span style="color: #0000FF;">NONE</span> <span style="color: #0000FF;">ON</span> Partitions<span style="color: #808080;">&#40;</span><span style="color: #000;">12</span><span style="color: #808080;">&#41;</span>
<span style="color: #808080;">&#41;</span>;
&nbsp;
<span style="color: #008080;">/* Apply compression to your partitioned index */</span>
<span style="color: #0000FF;">ALTER</span> <span style="color: #0000FF;">INDEX</span> YourPartitionedIndex
    <span style="color: #0000FF;">ON</span> dbo.<span style="color: #202020;">yourTableName</span>
    Rebuild Partition <span style="color: #808080;">=</span> All
    <span style="color: #0000FF;">WITH</span> 
    <span style="color: #808080;">&#40;</span>
      Data_Compression <span style="color: #808080;">=</span> Page <span style="color: #0000FF;">ON</span> Partitions<span style="color: #808080;">&#40;</span><span style="color: #000;">1</span> <span style="color: #0000FF;">TO</span> <span style="color: #000;">9</span><span style="color: #808080;">&#41;</span>
    , Data_Compression <span style="color: #808080;">=</span> <span style="color: #0000FF;">ROW</span>  <span style="color: #0000FF;">ON</span> Partitions<span style="color: #808080;">&#40;</span><span style="color: #000;">10</span> <span style="color: #0000FF;">TO</span> <span style="color: #000;">11</span><span style="color: #808080;">&#41;</span> 
    , Data_Compression <span style="color: #808080;">=</span> <span style="color: #0000FF;">NONE</span> <span style="color: #0000FF;">ON</span> Partitions<span style="color: #808080;">&#40;</span><span style="color: #000;">12</span><span style="color: #808080;">&#41;</span>
    <span style="color: #808080;">&#41;</span>;
&nbsp;
<span style="color: #008080;">/* Apply compression to your unpartitioned index */</span>
<span style="color: #0000FF;">ALTER</span> <span style="color: #0000FF;">INDEX</span> YourUnpartitionedIndex
    <span style="color: #0000FF;">ON</span> dbo.<span style="color: #202020;">yourTableName</span>
    Rebuild <span style="color: #0000FF;">WITH</span> <span style="color: #808080;">&#40;</span>Data_Compression <span style="color: #808080;">=</span> <span style="color: #0000FF;">ROW</span><span style="color: #808080;">&#41;</span>;</pre></div></div>

<p>A couple of things to note.  In all of our proof-of-concept testing, we found that compression significantly reduced query execution time, reads (IO), and storage.  However, CPU was also increased significantly.  The results were more dramatic, both good and bad, with page compression versus row compression.  Still, for our older partitions, which aren't queried regularly, it made sense to turn on page compression.  The newer partitions receive row compression, and the newest partitions, which are still queried very regularly by routine processes, were left completely uncompressed.  This seems to strike a nice balance in our environment, but of course, results will vary depending on how you use your data.</p>
<p>Something to be aware of is that compressing your clustered index does *not* compress your non-clustered indexes; those are separate operations.  Lastly, for those who are curious, it took us about 1 minute to apply row compression and about 7 minutes to apply page compression to partitions averaging 30 million rows.</p>
<p>Looking for more information on table partitioning?  Check out my <a href="http://sqlfool.com/2008/11/partitioning-101/" target="_blank">overview of partitioning</a>, my <a href="http://sqlfool.com/2008/11/102/" target="_blank">example code</a>, and my article on <a href="http://sqlfool.com/2008/12/indexing-for-partitioned-tables/" target="_blank">indexing on partitioned tables</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://sqlfool.com/2009/10/partitioning-tricks/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Undocumented Function in SQL 2008</title>
		<link>http://sqlfool.com/2009/09/undocumented-function-in-sql-2008/</link>
		<comments>http://sqlfool.com/2009/09/undocumented-function-in-sql-2008/#comments</comments>
		<pubDate>Wed, 02 Sep 2009 01:39:52 +0000</pubDate>
		<dc:creator>Michelle Ufford</dc:creator>
				<category><![CDATA[Internals]]></category>
		<category><![CDATA[SQL 2008]]></category>
		<category><![CDATA[Syndication]]></category>
		<category><![CDATA[2008]]></category>
		<category><![CDATA[pages]]></category>
		<category><![CDATA[undocumented commands]]></category>

		<guid isPermaLink="false">http://sqlfool.com/?p=1154</guid>
		<description><![CDATA[If you've been following my blog for a little while, you'll know that I'm a fan of SQL Server internals. There's a lot that can be learned or better understood by rolling up your sleeves and getting into the nitty-gritty of data pages (i.e. see my post on Overhead in Non-Unique Clustered Indexes). So imagine [...]]]></description>
			<content:encoded><![CDATA[<p>If you've been following my blog for a little while, you'll know that I'm a fan of SQL Server internals.  There's a lot that can be learned or better understood by rolling up your sleeves and getting into the nitty-gritty of data pages (i.e. see my post on <a href="http://sqlfool.com/2009/05/overhead-i-non-unique-clustered-indexes/" target="_blank">Overhead in Non-Unique Clustered Indexes</a>).  So imagine how happy I was when my co-worker Jeff shared an undocumented function with me today that retrieves the file number, page number, and slot number of a single record.  Very cool!  Well, at least to me.  So now let's see how you can use it.</p>
<p>The fn_physLocCracker function can be called in the following way:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">SELECT</span> <span style="color: #0000FF;">TOP</span> <span style="color: #000;">100</span> plc.<span style="color: #808080;">*</span>, soh.<span style="color: #202020;">SalesOrderID</span>
<span style="color: #0000FF;">FROM</span> Sales.<span style="color: #202020;">SalesOrderHeader</span> <span style="color: #0000FF;">AS</span> soh
Cross Apply sys.<span style="color: #202020;">fn_physLocCracker</span> <span style="color: #808080;">&#40;</span><span style="color: #808080;">%%</span>physloc<span style="color: #808080;">%%</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> plc;</pre></div></div>

<p>Results (just a sample):</p>

<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">file_id     page_id     slot_id     SalesOrderID
----------- ----------- ----------- ------------
1           14032       0           43659
1           14032       1           43660
1           14032       2           43661
1           14032       3           43662
1           14032       4           43663</pre></div></div>

<p>If you look at the <a href="http://msdn.microsoft.com/en-us/library/ms176112.aspx" target="_blank">sp_helptext</a> for sys.fn_physLocCracker, %%physloc%% is apparently a virtual column that contains information on where the record is stored.  In fact, you can even append %%physloc%% to your column list if you want to see how the information is stored.  But for our purposes, we now have a file number, page number, and slot number.  What do we do with it?</p>
<p>Well, you can use the <a href="http://sqlfool.com/2009/05/page-internals-investigation-proc/" target="_blank">investigation proc I wrote</a> to retrieve the actual data page:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">EXECUTE</span> dba_viewPageData_sp 
      @databaseName <span style="color: #808080;">=</span> <span style="color: #FF0000;">'AdventureWorks'</span>
    , @fileNumber <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
    , @pageNumber <span style="color: #808080;">=</span> <span style="color: #000;">14032</span>;</pre></div></div>

<p>Results (just a sample):</p>

<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">Slot 0 Column 1 Offset 0x4 Length 4 Length (physical) 4
&nbsp;
SalesOrderID = 43659                 
&nbsp;
Slot 0 Column 2 Offset 0x8 Length 1 Length (physical) 1
&nbsp;
RevisionNumber = 1                   
&nbsp;
Slot 0 Column 3 Offset 0x9 Length 8 Length (physical) 8
&nbsp;
OrderDate = 2001-07-01 00:00:00.000  
&nbsp;
Slot 0 Column 4 Offset 0x11 Length 8 Length (physical) 8
&nbsp;
DueDate = 2001-07-13 00:00:00.000</pre></div></div>

<p>Neat, huh?  So why would you use it to look up the data page and file number when you can just pass the table name and index name to my proc and retrieve data pages?  Well, my investigation proc will retrieve data pages for any index type -- the fn_physLocCracker function will only retrieve data for the clustered index -- but it will not retrieve the data page for a specific record.  So just something to be aware of.</p>
<p>That's all for now.  Back to the #24HoursOfPASS!  <img src='http://sqlfool.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://sqlfool.com/2009/09/undocumented-function-in-sql-2008/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Index Defrag Script, v3.0</title>
		<link>http://sqlfool.com/2009/06/index-defrag-script-v30/</link>
		<comments>http://sqlfool.com/2009/06/index-defrag-script-v30/#comments</comments>
		<pubDate>Wed, 24 Jun 2009 00:37:24 +0000</pubDate>
		<dc:creator>Michelle Ufford</dc:creator>
				<category><![CDATA[Performance & Tuning]]></category>
		<category><![CDATA[SQL 2008]]></category>
		<category><![CDATA[Syndication]]></category>
		<category><![CDATA[T-SQL Scripts]]></category>
		<category><![CDATA[defrag]]></category>
		<category><![CDATA[defragment]]></category>
		<category><![CDATA[indexes]]></category>
		<category><![CDATA[maintenace]]></category>
		<category><![CDATA[script]]></category>
		<category><![CDATA[tuning]]></category>

		<guid isPermaLink="false">http://sqlfool.com/?p=1072</guid>
		<description><![CDATA[UPDATE: This script has been significantly updated. Find the latest version here: Index Defrag Script, v4.0 I've just completed the latest version of my index defrag script! Here's a brief list of the updates: Fixed a bug with the LOB logic. In the previous version, after a LOB was encountered, all subsequent indexes would be [...]]]></description>
			<content:encoded><![CDATA[<p><strong>UPDATE:</strong>  This script has been significantly updated.  Find the latest version here:  <a href="http://sqlfool.com/2010/04/index-defrag-script-v4-0/">Index Defrag Script, v4.0</a></p>
<p>I've just completed the latest version of my index defrag script!  Here's a brief list of the updates:</p>
<ul>
<li>Fixed a bug with the LOB logic.  In the previous version, after a LOB was encountered, all subsequent indexes would be reorganized.</li>
<li>Added support for stat rebuilds after the index defrag is complete (@rebuildStats)</li>
<li>Added an exclusion list table (dba_indexDefragExclusion) to support index scheduling</li>
<li>Modified logging to show which defrags are "in progress"; added columns to dba_indexDefragLog</li>
<li>Added support for the defrag of the model and msdb databases</li>
<li>Added @scanMode as a configurable parameter</li>
</ul>
<p>So what can this index defrag script do?  Well, for starters, you can:</p>
<ul>
<li>Schedule it to run with the default settings; it works "right out of the box" with no additional configuration necessary</li>
<li>Run this one script from a centralized database for all databases on a server</li>
<li>Run this script for a specific database or table</li>
<li>Configure custom threshold limits and the point at which a rebuild should be performed (instead of a reorganize)</li>
<li>Defrag individual partitions</li>
<li>Log its actions and the duration of the defrag</li>
<li>Run in "commands only" mode (@executeSQL = 0, @printCommands = 1)</li>
<li>Customize performance parameters such as @maxDopRestriction and @defragDelay to minimize impact on the server</li>
<li>Schedule specific indexes to only be defragged on weekends, or every other day</li>
</ul>
<p>To use this last option, you need to add a record to the dba_indexDefragExclusion table.  I think all of the columns are pretty self-explanatory except the [exclusionMask] column.  The way this works is each day of the week is assigned a value:<br />
1=Sunday, 2=Monday, 4=Tuesday, 8=Wednesday, 16=Thursday, 32=Friday, 64=Saturday</p>
<p>Take a SUM of the values for the days that you want <strong>excluded</strong>.  So if you want an index to only be defragged on weekends, you would add up Monday through Friday (2+4+8+16+32) and use a value of 62 for the exclusionMask column.  For a little more information on how this works, check out my blog post on <a href="http://sqlfool.com/2009/02/bitwise-operations/" target="_blank">Bitwise Operations</a>.</p>
<p>Please note:  if you don't insert any records into the dba_indexDefragExclusion table, by default all indexes will be defragged every run-time if they exceed the specified thresholds.  This is normal behavior and may be perfectly fine in your environment.  However, if the dba_indexDefragExclusion table does not exist, the script will fail.  </p>
<p>I try to document each parameter within the code, so check the comments section in the script for a full list of parameters and what they do.  </p>
<p>Special thanks to everyone who helped beta test this script!  <img src='http://sqlfool.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Without further ado, the script:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #008080;">/* Drop Table Scripts:
Drop Table dbo.dba_indexDefragLog;
Drop Table dbo.dba_indexDefragExclusion;
*/</span>
<span style="color: #0000FF;">IF</span> Not Exists<span style="color: #808080;">&#40;</span><span style="color: #0000FF;">SELECT</span> <span style="color: #808080;">&#91;</span><span style="color: #FF00FF;">OBJECT_ID</span><span style="color: #808080;">&#93;</span> <span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">tables</span> 
    <span style="color: #0000FF;">WHERE</span> <span style="color: #808080;">&#91;</span>name<span style="color: #808080;">&#93;</span> In <span style="color: #808080;">&#40;</span>N<span style="color: #FF0000;">'dba_indexDefragLog'</span>, <span style="color: #FF0000;">'dba_indexDefragExclusion'</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span>
<span style="color: #0000FF;">BEGIN</span>
&nbsp;
    <span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">TABLE</span> dbo.<span style="color: #202020;">dba_indexDefragLog</span>
    <span style="color: #808080;">&#40;</span>
          indexDefrag_id    <span style="color: #0000FF;">INT</span> <span style="color: #0000FF;">IDENTITY</span><span style="color: #808080;">&#40;</span><span style="color: #000;">1</span>,<span style="color: #000;">1</span><span style="color: #808080;">&#41;</span>   Not Null
        , databaseID        <span style="color: #0000FF;">INT</span>                 Not Null
        , databaseName      <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">128</span><span style="color: #808080;">&#41;</span>       Not Null
        , objectID          <span style="color: #0000FF;">INT</span>                 Not Null
        , objectName        <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">128</span><span style="color: #808080;">&#41;</span>       Not Null
        , indexID           <span style="color: #0000FF;">INT</span>                 Not Null
        , indexName         <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">128</span><span style="color: #808080;">&#41;</span>       Not Null
        , partitionNumber   <span style="color: #0000FF;">SMALLINT</span>            Not Null
        , fragmentation     <span style="color: #0000FF;">FLOAT</span>               Not Null
        , page_count        <span style="color: #0000FF;">INT</span>                 Not Null
        , dateTimeStart     <span style="color: #0000FF;">DATETIME</span>            Not Null
        , dateTimeEnd       <span style="color: #0000FF;">DATETIME</span>            Null
        , durationSeconds   <span style="color: #0000FF;">INT</span>                 Null
&nbsp;
        <span style="color: #0000FF;">CONSTRAINT</span> PK_indexDefragLog 
            <span style="color: #0000FF;">PRIMARY</span> <span style="color: #0000FF;">KEY</span> <span style="color: #0000FF;">CLUSTERED</span> <span style="color: #808080;">&#40;</span>indexDefrag_id<span style="color: #808080;">&#41;</span>
    <span style="color: #808080;">&#41;</span>;
&nbsp;
    <span style="color: #0000FF;">PRINT</span> <span style="color: #FF0000;">'dba_indexDefragLog Table Created'</span>;
&nbsp;
    <span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">TABLE</span> dbo.<span style="color: #202020;">dba_indexDefragExclusion</span>
    <span style="color: #808080;">&#40;</span>
          databaseID        <span style="color: #0000FF;">INT</span>                 Not Null
        , databaseName      <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">128</span><span style="color: #808080;">&#41;</span>       Not Null
        , objectID          <span style="color: #0000FF;">INT</span>                 Not Null
        , objectName        <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">128</span><span style="color: #808080;">&#41;</span>       Not Null
        , indexID           <span style="color: #0000FF;">INT</span>                 Not Null
        , indexName         <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">128</span><span style="color: #808080;">&#41;</span>       Not Null
        , exclusionMask     <span style="color: #0000FF;">INT</span>                 Not Null
            <span style="color: #008080;">/* 1=Sunday, 2=Monday, 4=Tuesday, 8=Wednesday, 16=Thursday, 32=Friday, 64=Saturday */</span>
&nbsp;
        <span style="color: #0000FF;">CONSTRAINT</span> PK_indexDefragExclusion 
            <span style="color: #0000FF;">PRIMARY</span> <span style="color: #0000FF;">KEY</span> <span style="color: #0000FF;">CLUSTERED</span> <span style="color: #808080;">&#40;</span>databaseID, objectID, indexID<span style="color: #808080;">&#41;</span>
    <span style="color: #808080;">&#41;</span>;
&nbsp;
    <span style="color: #0000FF;">PRINT</span> <span style="color: #FF0000;">'dba_indexDefragExclusion Table Created'</span>;
&nbsp;
<span style="color: #0000FF;">END</span>
<span style="color: #0000FF;">ELSE</span>
    <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'One or more tables already exist.  Please drop or rename before proceeding.'</span>, <span style="color: #000;">16</span>, <span style="color: #000;">0</span><span style="color: #808080;">&#41;</span>;
&nbsp;
<span style="color: #0000FF;">IF</span> <span style="color: #FF00FF;">OBJECTPROPERTY</span><span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">OBJECT_ID</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'dbo.dba_indexDefrag_sp'</span><span style="color: #808080;">&#41;</span>, N<span style="color: #FF0000;">'IsProcedure'</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
<span style="color: #0000FF;">BEGIN</span>
    <span style="color: #0000FF;">DROP</span> <span style="color: #0000FF;">PROCEDURE</span> dbo.<span style="color: #202020;">dba_indexDefrag_sp</span>;
    <span style="color: #0000FF;">PRINT</span> <span style="color: #FF0000;">'Procedure dba_indexDefrag_sp dropped'</span>;
<span style="color: #0000FF;">END</span>;
Go
&nbsp;
&nbsp;
<span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">PROCEDURE</span> dbo.<span style="color: #202020;">dba_indexDefrag_sp</span>
&nbsp;
    <span style="color: #008080;">/* Declare Parameters */</span>
      @minFragmentation     <span style="color: #0000FF;">FLOAT</span>           <span style="color: #808080;">=</span> <span style="color: #000;">5.0</span>  
        <span style="color: #008080;">/* in percent, will not defrag if fragmentation less than specified */</span>
    , @rebuildThreshold     <span style="color: #0000FF;">FLOAT</span>           <span style="color: #808080;">=</span> <span style="color: #000;">30.0</span>  
        <span style="color: #008080;">/* in percent, greater than @rebuildThreshold will result in rebuild instead of reorg */</span>
    , @executeSQL           <span style="color: #0000FF;">BIT</span>             <span style="color: #808080;">=</span> <span style="color: #000;">1</span>     
        <span style="color: #008080;">/* 1 = execute; 0 = print command only */</span>
    , @<span style="color: #0000FF;">DATABASE</span>             <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">128</span><span style="color: #808080;">&#41;</span>    <span style="color: #808080;">=</span> Null
        <span style="color: #008080;">/* Option to specify a database name; null will return all */</span>
    , @tableName            <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">4000</span><span style="color: #808080;">&#41;</span>   <span style="color: #808080;">=</span> Null  <span style="color: #008080;">-- databaseName.schema.tableName</span>
        <span style="color: #008080;">/* Option to specify a table name; null will return all */</span>
    , @scanMode             <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">10</span><span style="color: #808080;">&#41;</span>     <span style="color: #808080;">=</span> N<span style="color: #FF0000;">'LIMITED'</span>
        <span style="color: #008080;">/* Options are LIMITED, SAMPLED, and DETAILED */</span>
    , @onlineRebuild        <span style="color: #0000FF;">BIT</span>             <span style="color: #808080;">=</span> <span style="color: #000;">1</span>     
        <span style="color: #008080;">/* 1 = online rebuild; 0 = offline rebuild; only in Enterprise */</span>
    , @maxDopRestriction    <span style="color: #0000FF;">TINYINT</span>         <span style="color: #808080;">=</span> Null
        <span style="color: #008080;">/* Option to restrict the number of processors for the operation; only in Enterprise */</span>
    , @printCommands        <span style="color: #0000FF;">BIT</span>             <span style="color: #808080;">=</span> <span style="color: #000;">0</span>     
        <span style="color: #008080;">/* 1 = print commands; 0 = do not print commands */</span>
    , @printFragmentation   <span style="color: #0000FF;">BIT</span>             <span style="color: #808080;">=</span> <span style="color: #000;">0</span>
        <span style="color: #008080;">/* 1 = print fragmentation prior to defrag; 
           0 = do not print */</span>
    , @defragDelay          <span style="color: #0000FF;">CHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">8</span><span style="color: #808080;">&#41;</span>         <span style="color: #808080;">=</span> <span style="color: #FF0000;">'00:00:05'</span>
        <span style="color: #008080;">/* time to wait between defrag commands */</span>
    , @debugMode            <span style="color: #0000FF;">BIT</span>             <span style="color: #808080;">=</span> <span style="color: #000;">0</span>
        <span style="color: #008080;">/* display some useful comments to help determine if/where issues occur */</span>
    , @rebuildStats         <span style="color: #0000FF;">BIT</span>             <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
        <span style="color: #008080;">/* option to rebuild stats after completed index defrags */</span>
&nbsp;
<span style="color: #0000FF;">AS</span>
<span style="color: #008080;">/*********************************************************************************
    Name:       dba_indexDefrag_sp
&nbsp;
    Author:     Michelle Ufford, http://sqlfool.com
&nbsp;
    Purpose:    Defrags all indexes for the current database
&nbsp;
    Notes:
&nbsp;
    CAUTION: TRANSACTION LOG SIZE SHOULD BE MONITORED CLOSELY WHEN DEFRAGMENTING.
&nbsp;
      @minFragmentation     defaulted to 10%, will not defrag if fragmentation 
                            is less than that
&nbsp;
      @rebuildThreshold     defaulted to 30% as recommended by Microsoft in BOL;
                            greater than 30% will result in rebuild instead
&nbsp;
      @executeSQL           1 = execute the SQL generated by this proc; 
                            0 = print command only
&nbsp;
      @database             Optional, specify specific database name to defrag;
                            If not specified, all non-system databases will
                            be defragged.
&nbsp;
      @tableName            Specify if you only want to defrag indexes for a 
                            specific table, format = databaseName.schema.tableName;
                            if not specified, all tables will be defragged.
&nbsp;
      @scanMode             Specifies which scan mode to use to determine
                            fragmentation levels.  Options are:
                            LIMITED - scans the parent level; quickest mode,
                                      recommended for most cases.
                            SAMPLED - samples 1% of all data pages; if less than
                                      10k pages, performs a DETAILED scan.
                            DETAILED - scans all data pages.  Use great care with
                                       this mode, as it can cause performance issues.
&nbsp;
      @onlineRebuild        1 = online rebuild; 
                            0 = offline rebuild
&nbsp;
      @maxDopRestriction    Option to specify a processor limit for index rebuilds
&nbsp;
      @printCommands        1 = print commands to screen; 
                            0 = do not print commands
&nbsp;
      @printFragmentation   1 = print fragmentation to screen;
                            0 = do not print fragmentation
&nbsp;
      @defragDelay          Time to wait between defrag commands; gives the
                            server a little time to catch up 
&nbsp;
      @debugMode            1 = display debug comments; helps with troubleshooting
                            0 = do not display debug comments
&nbsp;
      @rebuildStats         Affects only statistics that need to be rebuilt
                            1 = rebuild stats
                            0 = do not rebuild stats
&nbsp;
    Called by:  SQL Agent Job or DBA
&nbsp;
    Date        Initials	Version Description
    ----------------------------------------------------------------------------
    2007-12-18  MFU         1.0     Initial Release
    2008-10-17  MFU         1.1     Added @defragDelay, CIX_temp_indexDefragList
    2008-11-17  MFU         1.2     Added page_count to log table
                                    , added @printFragmentation option
    2009-03-17  MFU         2.0     Provided support for centralized execution
                                    , consolidated Enterprise &amp; Standard versions
                                    , added @debugMode, @maxDopRestriction
                                    , modified LOB and partition logic  
    2009-06-18  MFU         3.0     Fixed bug in LOB logic, added @scanMode option
                                    , added support for stat rebuilds (@rebuildStats)
                                    , support model and msdb defrag
                                    , added columns to the dba_indexDefragLog table
                                    , modified logging to show &quot;in progress&quot; defrags
                                    , added defrag exclusion list (scheduling)
*********************************************************************************
    Exec dbo.dba_indexDefrag_sp
          @executeSQL           = 0
        , @printCommands        = 1
        , @debugMode            = 1
        , @printFragmentation   = 1;
*********************************************************************************/</span>																
&nbsp;
<span style="color: #0000FF;">SET</span> <span style="color: #0000FF;">NOCOUNT</span> <span style="color: #0000FF;">ON</span>;
<span style="color: #0000FF;">SET</span> XACT_Abort <span style="color: #0000FF;">ON</span>;
<span style="color: #0000FF;">SET</span> Ansi_Padding <span style="color: #0000FF;">ON</span>;
<span style="color: #0000FF;">SET</span> Ansi_Warnings <span style="color: #0000FF;">ON</span>;
<span style="color: #0000FF;">SET</span> ArithAbort <span style="color: #0000FF;">ON</span>;
<span style="color: #0000FF;">SET</span> Concat_Null_Yields_Null <span style="color: #0000FF;">ON</span>;
<span style="color: #0000FF;">SET</span> Numeric_RoundAbort <span style="color: #0000FF;">OFF</span>;
<span style="color: #0000FF;">SET</span> Quoted_Identifier <span style="color: #0000FF;">ON</span>;
&nbsp;
<span style="color: #0000FF;">BEGIN</span>
&nbsp;
    <span style="color: #0000FF;">IF</span> @debugMode <span style="color: #808080;">=</span> <span style="color: #000;">1</span> <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'Undusting the cogs and starting up...'</span>, <span style="color: #000;">0</span>, <span style="color: #000;">42</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">WITH</span> NoWait;
&nbsp;
    <span style="color: #008080;">/* Declare our variables */</span>
    <span style="color: #0000FF;">DECLARE</span>   @objectID             <span style="color: #0000FF;">INT</span>
            , @databaseID           <span style="color: #0000FF;">INT</span>
            , @databaseName         <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">128</span><span style="color: #808080;">&#41;</span>
            , @indexID              <span style="color: #0000FF;">INT</span>
            , @partitionCount       <span style="color: #0000FF;">BIGINT</span>
            , @schemaName           <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">128</span><span style="color: #808080;">&#41;</span>
            , @objectName           <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">128</span><span style="color: #808080;">&#41;</span>
            , @indexName            <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">128</span><span style="color: #808080;">&#41;</span>
            , @partitionNumber      <span style="color: #0000FF;">SMALLINT</span>
            , @fragmentation        <span style="color: #0000FF;">FLOAT</span>
            , @pageCount            <span style="color: #0000FF;">INT</span>
            , @sqlCommand           <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">4000</span><span style="color: #808080;">&#41;</span>
            , @rebuildCommand       <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">200</span><span style="color: #808080;">&#41;</span>
            , @dateTimeStart        <span style="color: #0000FF;">DATETIME</span>
            , @dateTimeEnd          <span style="color: #0000FF;">DATETIME</span>
            , @containsLOB          <span style="color: #0000FF;">BIT</span>
            , @editionCheck         <span style="color: #0000FF;">BIT</span>
            , @debugMessage         <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">128</span><span style="color: #808080;">&#41;</span>
            , @updateSQL            <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">4000</span><span style="color: #808080;">&#41;</span>
            , @partitionSQL         <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">4000</span><span style="color: #808080;">&#41;</span>
            , @partitionSQL_Param   <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">1000</span><span style="color: #808080;">&#41;</span>
            , @LOB_SQL              <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">4000</span><span style="color: #808080;">&#41;</span>
            , @LOB_SQL_Param        <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">1000</span><span style="color: #808080;">&#41;</span>
            , @rebuildStatsID       <span style="color: #0000FF;">INT</span>
            , @rebuildStatsSQL      <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">1000</span><span style="color: #808080;">&#41;</span>
            , @indexDefrag_id       <span style="color: #0000FF;">INT</span>;
&nbsp;
    <span style="color: #008080;">/* Create our temporary tables */</span>
    <span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">TABLE</span> #indexDefragList
    <span style="color: #808080;">&#40;</span>
          databaseID        <span style="color: #0000FF;">INT</span>
        , databaseName      <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">128</span><span style="color: #808080;">&#41;</span>
        , objectID          <span style="color: #0000FF;">INT</span>
        , indexID           <span style="color: #0000FF;">INT</span>
        , partitionNumber   <span style="color: #0000FF;">SMALLINT</span>
        , fragmentation     <span style="color: #0000FF;">FLOAT</span>
        , page_count        <span style="color: #0000FF;">INT</span>
        , defragStatus      <span style="color: #0000FF;">BIT</span>
        , schemaName        <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">128</span><span style="color: #808080;">&#41;</span>   Null
        , objectName        <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">128</span><span style="color: #808080;">&#41;</span>   Null
        , indexName         <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">128</span><span style="color: #808080;">&#41;</span>   Null
    <span style="color: #808080;">&#41;</span>;
&nbsp;
    <span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">TABLE</span> #databaseList
    <span style="color: #808080;">&#40;</span>
          databaseID        <span style="color: #0000FF;">INT</span>
        , databaseName      <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">128</span><span style="color: #808080;">&#41;</span>
        , scanStatus        <span style="color: #0000FF;">BIT</span>
        , statsStatus       <span style="color: #0000FF;">BIT</span>
    <span style="color: #808080;">&#41;</span>;
&nbsp;
    <span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">TABLE</span> #processor 
    <span style="color: #808080;">&#40;</span>
          <span style="color: #808080;">&#91;</span><span style="color: #0000FF;">INDEX</span><span style="color: #808080;">&#93;</span>           <span style="color: #0000FF;">INT</span>
        , Name              <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">128</span><span style="color: #808080;">&#41;</span>
        , Internal_Value    <span style="color: #0000FF;">INT</span>
        , Character_Value   <span style="color: #0000FF;">INT</span>
    <span style="color: #808080;">&#41;</span>;
&nbsp;
    <span style="color: #0000FF;">IF</span> @debugMode <span style="color: #808080;">=</span> <span style="color: #000;">1</span> <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'Beginning validation...'</span>, <span style="color: #000;">0</span>, <span style="color: #000;">42</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">WITH</span> NoWait;
&nbsp;
    <span style="color: #008080;">/* Just a little validation... */</span>
    <span style="color: #0000FF;">IF</span> @minFragmentation Not Between <span style="color: #000;">0.00</span> And <span style="color: #000;">100.0</span>
        <span style="color: #0000FF;">SET</span> @minFragmentation <span style="color: #808080;">=</span> <span style="color: #000;">10.0</span>;
&nbsp;
    <span style="color: #0000FF;">IF</span> @rebuildThreshold Not Between <span style="color: #000;">0.00</span> And <span style="color: #000;">100.0</span>
        <span style="color: #0000FF;">SET</span> @rebuildThreshold <span style="color: #808080;">=</span> <span style="color: #000;">30.0</span>;
&nbsp;
    <span style="color: #0000FF;">IF</span> @defragDelay Not Like <span style="color: #FF0000;">'00:[0-5][0-9]:[0-5][0-9]'</span>
        <span style="color: #0000FF;">SET</span> @defragDelay <span style="color: #808080;">=</span> <span style="color: #FF0000;">'00:00:05'</span>;
&nbsp;
    <span style="color: #0000FF;">IF</span> @scanMode Not In <span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'LIMITED'</span>, <span style="color: #FF0000;">'SAMPLED'</span>, <span style="color: #FF0000;">'DETAILED'</span><span style="color: #808080;">&#41;</span>
        <span style="color: #0000FF;">SET</span> @scanMode <span style="color: #808080;">=</span> <span style="color: #FF0000;">'LIMITED'</span>;
&nbsp;
    <span style="color: #008080;">/* Make sure we're not exceeding the number of processors we have available */</span>
    <span style="color: #0000FF;">INSERT</span> <span style="color: #0000FF;">INTO</span> #processor
    <span style="color: #0000FF;">EXECUTE</span> <span style="color: #AF0000;">XP_MSVER</span> <span style="color: #FF0000;">'ProcessorCount'</span>;
&nbsp;
    <span style="color: #0000FF;">IF</span> @maxDopRestriction <span style="color: #0000FF;">IS</span> Not Null And @maxDopRestriction <span style="color: #808080;">&gt;</span> <span style="color: #808080;">&#40;</span><span style="color: #0000FF;">SELECT</span> Internal_Value <span style="color: #0000FF;">FROM</span> #processor<span style="color: #808080;">&#41;</span>
        <span style="color: #0000FF;">SELECT</span> @maxDopRestriction <span style="color: #808080;">=</span> Internal_Value
        <span style="color: #0000FF;">FROM</span> #processor;
&nbsp;
    <span style="color: #008080;">/* Check our server version; 1804890536 = Enterprise, 610778273 = Enterprise Evaluation, -2117995310 = Developer */</span>
    <span style="color: #0000FF;">IF</span> <span style="color: #808080;">&#40;</span><span style="color: #0000FF;">SELECT</span> <span style="color: #FF00FF;">SERVERPROPERTY</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'EditionID'</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span> In <span style="color: #808080;">&#40;</span><span style="color: #000;">1804890536</span>, <span style="color: #000;">610778273</span>, <span style="color: #808080;">-</span><span style="color: #000;">2117995310</span><span style="color: #808080;">&#41;</span> 
        <span style="color: #0000FF;">SET</span> @editionCheck <span style="color: #808080;">=</span> <span style="color: #000;">1</span> <span style="color: #008080;">-- supports online rebuilds</span>
    <span style="color: #0000FF;">ELSE</span>
        <span style="color: #0000FF;">SET</span> @editionCheck <span style="color: #808080;">=</span> <span style="color: #000;">0</span>; <span style="color: #008080;">-- does not support online rebuilds</span>
&nbsp;
    <span style="color: #0000FF;">IF</span> @debugMode <span style="color: #808080;">=</span> <span style="color: #000;">1</span> <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'Grabbing a list of our databases...'</span>, <span style="color: #000;">0</span>, <span style="color: #000;">42</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">WITH</span> NoWait;
&nbsp;
    <span style="color: #008080;">/* Retrieve the list of databases to investigate */</span>
    <span style="color: #0000FF;">INSERT</span> <span style="color: #0000FF;">INTO</span> #databaseList
    <span style="color: #0000FF;">SELECT</span> database_id
        , name
        , <span style="color: #000;">0</span> <span style="color: #008080;">-- not scanned yet for fragmentation</span>
        , <span style="color: #000;">0</span> <span style="color: #008080;">-- statistics not yet updated</span>
    <span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">databases</span>
    <span style="color: #0000FF;">WHERE</span> name <span style="color: #808080;">=</span> IsNull<span style="color: #808080;">&#40;</span>@<span style="color: #0000FF;">DATABASE</span>, name<span style="color: #808080;">&#41;</span>
        And <span style="color: #808080;">&#91;</span>name<span style="color: #808080;">&#93;</span> Not In <span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'master'</span>, <span style="color: #FF0000;">'tempdb'</span><span style="color: #808080;">&#41;</span><span style="color: #008080;">-- exclude system databases</span>
        And <span style="color: #808080;">&#91;</span><span style="color: #0000FF;">STATE</span><span style="color: #808080;">&#93;</span> <span style="color: #808080;">=</span> <span style="color: #000;">0</span>; <span style="color: #008080;">-- state must be ONLINE</span>
&nbsp;
    <span style="color: #0000FF;">IF</span> @debugMode <span style="color: #808080;">=</span> <span style="color: #000;">1</span> <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'Looping through our list of databases and checking for fragmentation...'</span>, <span style="color: #000;">0</span>, <span style="color: #000;">42</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">WITH</span> NoWait;
&nbsp;
    <span style="color: #008080;">/* Loop through our list of databases */</span>
    <span style="color: #0000FF;">WHILE</span> <span style="color: #808080;">&#40;</span><span style="color: #0000FF;">SELECT</span> <span style="color: #FF00FF;">COUNT</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">*</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">FROM</span> #databaseList <span style="color: #0000FF;">WHERE</span> scanStatus <span style="color: #808080;">=</span> <span style="color: #000;">0</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">&gt;</span> <span style="color: #000;">0</span>
    <span style="color: #0000FF;">BEGIN</span>
&nbsp;
        <span style="color: #0000FF;">SELECT</span> <span style="color: #0000FF;">TOP</span> <span style="color: #000;">1</span> @databaseID <span style="color: #808080;">=</span> databaseID
        <span style="color: #0000FF;">FROM</span> #databaseList
        <span style="color: #0000FF;">WHERE</span> scanStatus <span style="color: #808080;">=</span> <span style="color: #000;">0</span>;
&nbsp;
        <span style="color: #0000FF;">SELECT</span> @debugMessage <span style="color: #808080;">=</span> <span style="color: #FF0000;">'  working on '</span> <span style="color: #808080;">+</span> <span style="color: #FF00FF;">DB_NAME</span><span style="color: #808080;">&#40;</span>@databaseID<span style="color: #808080;">&#41;</span> <span style="color: #808080;">+</span> <span style="color: #FF0000;">'...'</span>;
&nbsp;
        <span style="color: #0000FF;">IF</span> @debugMode <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
            <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span>@debugMessage, <span style="color: #000;">0</span>, <span style="color: #000;">42</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">WITH</span> NoWait;
&nbsp;
       <span style="color: #008080;">/* Determine which indexes to defrag using our user-defined parameters */</span>
        <span style="color: #0000FF;">INSERT</span> <span style="color: #0000FF;">INTO</span> #indexDefragList
        <span style="color: #0000FF;">SELECT</span>
              database_id <span style="color: #0000FF;">AS</span> databaseID
            , <span style="color: #FF00FF;">QUOTENAME</span><span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">DB_NAME</span><span style="color: #808080;">&#40;</span>database_id<span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'databaseName'</span>
            , <span style="color: #808080;">&#91;</span><span style="color: #FF00FF;">OBJECT_ID</span><span style="color: #808080;">&#93;</span> <span style="color: #0000FF;">AS</span> objectID
            , index_id <span style="color: #0000FF;">AS</span> indexID
            , partition_number <span style="color: #0000FF;">AS</span> partitionNumber
            , avg_fragmentation_in_percent <span style="color: #0000FF;">AS</span> fragmentation
            , page_count 
            , <span style="color: #000;">0</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'defragStatus'</span> <span style="color: #008080;">/* 0 = unprocessed, 1 = processed */</span>
            , Null <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'schemaName'</span>
            , Null <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'objectName'</span>
            , Null <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'indexName'</span>
        <span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">dm_db_index_physical_stats</span> <span style="color: #808080;">&#40;</span>@databaseID, <span style="color: #FF00FF;">OBJECT_ID</span><span style="color: #808080;">&#40;</span>@tableName<span style="color: #808080;">&#41;</span>, Null , Null, @scanMode<span style="color: #808080;">&#41;</span>
        <span style="color: #0000FF;">WHERE</span> avg_fragmentation_in_percent <span style="color: #808080;">&gt;=</span> @minFragmentation 
            And index_id <span style="color: #808080;">&gt;</span> <span style="color: #000;">0</span> <span style="color: #008080;">-- ignore heaps</span>
            And page_count <span style="color: #808080;">&gt;</span> <span style="color: #000;">8</span> <span style="color: #008080;">-- ignore objects with less than 1 extent</span>
            And index_level <span style="color: #808080;">=</span> <span style="color: #000;">0</span> <span style="color: #008080;">-- leaf-level nodes only, supports @scanMode</span>
        <span style="color: #0000FF;">OPTION</span> <span style="color: #808080;">&#40;</span>MaxDop <span style="color: #000;">2</span><span style="color: #808080;">&#41;</span>;
&nbsp;
        <span style="color: #008080;">/* Keep track of which databases have already been scanned */</span>
        <span style="color: #0000FF;">UPDATE</span> #databaseList
        <span style="color: #0000FF;">SET</span> scanStatus <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
        <span style="color: #0000FF;">WHERE</span> databaseID <span style="color: #808080;">=</span> @databaseID;
&nbsp;
    <span style="color: #0000FF;">END</span>
&nbsp;
    <span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">CLUSTERED</span> <span style="color: #0000FF;">INDEX</span> CIX_temp_indexDefragList
        <span style="color: #0000FF;">ON</span> #indexDefragList<span style="color: #808080;">&#40;</span>databaseID, objectID, indexID, partitionNumber<span style="color: #808080;">&#41;</span>;
&nbsp;
    <span style="color: #008080;">/* Delete any indexes from our to-do that are also in our exclusion list for today */</span>
    <span style="color: #0000FF;">DELETE</span> idl
    <span style="color: #0000FF;">FROM</span> #indexDefragList <span style="color: #0000FF;">AS</span> idl
    Join dbo.<span style="color: #202020;">dba_indexDefragExclusion</span> <span style="color: #0000FF;">AS</span> ide
        <span style="color: #0000FF;">ON</span> idl.<span style="color: #202020;">databaseID</span> <span style="color: #808080;">=</span> ide.<span style="color: #202020;">databaseID</span>
        And idl.<span style="color: #202020;">objectID</span> <span style="color: #808080;">=</span> ide.<span style="color: #202020;">objectID</span>
        And idl.<span style="color: #202020;">indexID</span> <span style="color: #808080;">=</span> ide.<span style="color: #202020;">indexID</span>
    <span style="color: #0000FF;">WHERE</span> exclusionMask <span style="color: #808080;">&amp;</span> <span style="color: #FF00FF;">POWER</span><span style="color: #808080;">&#40;</span><span style="color: #000;">2</span>, <span style="color: #FF00FF;">DATEPART</span><span style="color: #808080;">&#40;</span>weekday, <span style="color: #FF00FF;">GETDATE</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">-</span><span style="color: #000;">1</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">&gt;</span> <span style="color: #000;">0</span>;
&nbsp;
    <span style="color: #0000FF;">SELECT</span> @debugMessage <span style="color: #808080;">=</span> <span style="color: #FF0000;">'Looping through our list... there'</span><span style="color: #FF0000;">'s '</span> <span style="color: #808080;">+</span> <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">COUNT</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">*</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">10</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">+</span> <span style="color: #FF0000;">' indexes to defrag!'</span>
    <span style="color: #0000FF;">FROM</span> #indexDefragList;
&nbsp;
    <span style="color: #0000FF;">IF</span> @debugMode <span style="color: #808080;">=</span> <span style="color: #000;">1</span> <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span>@debugMessage, <span style="color: #000;">0</span>, <span style="color: #000;">42</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">WITH</span> NoWait;
&nbsp;
    <span style="color: #008080;">/* Begin our loop for defragging */</span>
    <span style="color: #0000FF;">WHILE</span> <span style="color: #808080;">&#40;</span><span style="color: #0000FF;">SELECT</span> <span style="color: #FF00FF;">COUNT</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">*</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">FROM</span> #indexDefragList <span style="color: #0000FF;">WHERE</span> defragStatus <span style="color: #808080;">=</span> <span style="color: #000;">0</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">&gt;</span> <span style="color: #000;">0</span>
    <span style="color: #0000FF;">BEGIN</span>
&nbsp;
        <span style="color: #0000FF;">IF</span> @debugMode <span style="color: #808080;">=</span> <span style="color: #000;">1</span> <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'  Picking an index to beat into shape...'</span>, <span style="color: #000;">0</span>, <span style="color: #000;">42</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">WITH</span> NoWait;
&nbsp;
        <span style="color: #008080;">/* Grab the most fragmented index first to defrag */</span>
        <span style="color: #0000FF;">SELECT</span> <span style="color: #0000FF;">TOP</span> <span style="color: #000;">1</span> 
              @objectID         <span style="color: #808080;">=</span> objectID
            , @indexID          <span style="color: #808080;">=</span> indexID
            , @databaseID       <span style="color: #808080;">=</span> databaseID
            , @databaseName     <span style="color: #808080;">=</span> databaseName
            , @fragmentation    <span style="color: #808080;">=</span> fragmentation
            , @partitionNumber  <span style="color: #808080;">=</span> partitionNumber
            , @pageCount        <span style="color: #808080;">=</span> page_count
        <span style="color: #0000FF;">FROM</span> #indexDefragList
        <span style="color: #0000FF;">WHERE</span> defragStatus <span style="color: #808080;">=</span> <span style="color: #000;">0</span>
        <span style="color: #0000FF;">ORDER</span> <span style="color: #0000FF;">BY</span> fragmentation <span style="color: #0000FF;">DESC</span>;
&nbsp;
        <span style="color: #0000FF;">IF</span> @debugMode <span style="color: #808080;">=</span> <span style="color: #000;">1</span> <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'  Looking up the specifics for our index...'</span>, <span style="color: #000;">0</span>, <span style="color: #000;">42</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">WITH</span> NoWait;
&nbsp;
        <span style="color: #008080;">/* Look up index information */</span>
        <span style="color: #0000FF;">SELECT</span> @updateSQL <span style="color: #808080;">=</span> N<span style="color: #FF0000;">'Update idl
            Set schemaName = QuoteName(s.name)
                , objectName = QuoteName(o.name)
                , indexName = QuoteName(i.name)
            From #indexDefragList As idl
            Inner Join '</span> <span style="color: #808080;">+</span> @databaseName <span style="color: #808080;">+</span> <span style="color: #FF0000;">'.sys.objects As o
                On idl.objectID = o.object_id
            Inner Join '</span> <span style="color: #808080;">+</span> @databaseName <span style="color: #808080;">+</span> <span style="color: #FF0000;">'.sys.indexes As i
                On o.object_id = i.object_id
            Inner Join '</span> <span style="color: #808080;">+</span> @databaseName <span style="color: #808080;">+</span> <span style="color: #FF0000;">'.sys.schemas As s
                On o.schema_id = s.schema_id
            Where o.object_id = '</span> <span style="color: #808080;">+</span> <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span>@objectID <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">10</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">+</span> <span style="color: #FF0000;">'
                And i.index_id = '</span> <span style="color: #808080;">+</span> <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span>@indexID <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">10</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">+</span> <span style="color: #FF0000;">'
                And i.type &gt; 0
                And idl.databaseID = '</span> <span style="color: #808080;">+</span> <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span>@databaseID <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">10</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span>;
&nbsp;
        <span style="color: #0000FF;">EXECUTE</span> <span style="color: #AF0000;">SP_EXECUTESQL</span> @updateSQL;
&nbsp;
        <span style="color: #008080;">/* Grab our object names */</span>
        <span style="color: #0000FF;">SELECT</span> @objectName  <span style="color: #808080;">=</span> objectName
            , @schemaName   <span style="color: #808080;">=</span> schemaName
            , @indexName    <span style="color: #808080;">=</span> indexName
        <span style="color: #0000FF;">FROM</span> #indexDefragList
        <span style="color: #0000FF;">WHERE</span> objectID <span style="color: #808080;">=</span> @objectID
            And indexID <span style="color: #808080;">=</span> @indexID
            And databaseID <span style="color: #808080;">=</span> @databaseID;
&nbsp;
        <span style="color: #0000FF;">IF</span> @debugMode <span style="color: #808080;">=</span> <span style="color: #000;">1</span> <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'  Grabbing the partition count...'</span>, <span style="color: #000;">0</span>, <span style="color: #000;">42</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">WITH</span> NoWait;
&nbsp;
        <span style="color: #008080;">/* Determine if the index is partitioned */</span>
        <span style="color: #0000FF;">SELECT</span> @partitionSQL <span style="color: #808080;">=</span> <span style="color: #FF0000;">'Select @partitionCount_OUT = Count(*)
                                    From '</span> <span style="color: #808080;">+</span> @databaseName <span style="color: #808080;">+</span> <span style="color: #FF0000;">'.sys.partitions
                                    Where object_id = '</span> <span style="color: #808080;">+</span> <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span>@objectID <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">10</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">+</span> <span style="color: #FF0000;">'
                                        And index_id = '</span> <span style="color: #808080;">+</span> <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span>@indexID <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">10</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">+</span> <span style="color: #FF0000;">';'</span>
            , @partitionSQL_Param <span style="color: #808080;">=</span> <span style="color: #FF0000;">'@partitionCount_OUT int OutPut'</span>;
&nbsp;
        <span style="color: #0000FF;">EXECUTE</span> <span style="color: #AF0000;">SP_EXECUTESQL</span> @partitionSQL, @partitionSQL_Param, @partitionCount_OUT <span style="color: #808080;">=</span> @partitionCount <span style="color: #0000FF;">OUTPUT</span>;
&nbsp;
        <span style="color: #0000FF;">IF</span> @debugMode <span style="color: #808080;">=</span> <span style="color: #000;">1</span> <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'  Seeing if there'</span><span style="color: #FF0000;">'s any LOBs to be handled...'</span>, <span style="color: #000;">0</span>, <span style="color: #000;">42</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">WITH</span> NoWait;
&nbsp;
        <span style="color: #008080;">/* Determine if the table contains LOBs */</span>
        <span style="color: #0000FF;">SELECT</span> @LOB_SQL <span style="color: #808080;">=</span> <span style="color: #FF0000;">' Select @containsLOB_OUT = Count(*)
                            From '</span> <span style="color: #808080;">+</span> @databaseName <span style="color: #808080;">+</span> <span style="color: #FF0000;">'.sys.columns With (NoLock) 
                            Where [object_id] = '</span> <span style="color: #808080;">+</span> <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span>@objectID <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">10</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">+</span> <span style="color: #FF0000;">'
                                And (system_type_id In (34, 35, 99)
                                        Or max_length = -1);'</span>
                            <span style="color: #008080;">/*  system_type_id --&gt; 34 = image, 35 = text, 99 = ntext
                                max_length = -1 --&gt; varbinary(max), varchar(max), nvarchar(max), xml */</span>
                , @LOB_SQL_Param <span style="color: #808080;">=</span> <span style="color: #FF0000;">'@containsLOB_OUT int OutPut'</span>;
&nbsp;
        <span style="color: #0000FF;">EXECUTE</span> <span style="color: #AF0000;">SP_EXECUTESQL</span> @LOB_SQL, @LOB_SQL_Param, @containsLOB_OUT <span style="color: #808080;">=</span> @containsLOB <span style="color: #0000FF;">OUTPUT</span>;
&nbsp;
        <span style="color: #0000FF;">IF</span> @debugMode <span style="color: #808080;">=</span> <span style="color: #000;">1</span> <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'  Building our SQL statements...'</span>, <span style="color: #000;">0</span>, <span style="color: #000;">42</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">WITH</span> NoWait;
&nbsp;
        <span style="color: #008080;">/* If there's not a lot of fragmentation, or if we have a LOB, we should reorganize */</span>
        <span style="color: #0000FF;">IF</span> @fragmentation <span style="color: #808080;">&lt;</span> @rebuildThreshold Or @containsLOB <span style="color: #808080;">&gt;=</span> <span style="color: #000;">1</span> Or @partitionCount <span style="color: #808080;">&gt;</span> <span style="color: #000;">1</span>
        <span style="color: #0000FF;">BEGIN</span>
&nbsp;
            <span style="color: #0000FF;">SET</span> @sqlCommand <span style="color: #808080;">=</span> N<span style="color: #FF0000;">'Alter Index '</span> <span style="color: #808080;">+</span> @indexName <span style="color: #808080;">+</span> N<span style="color: #FF0000;">' On '</span> <span style="color: #808080;">+</span> @databaseName <span style="color: #808080;">+</span> N<span style="color: #FF0000;">'.'</span> 
                                <span style="color: #808080;">+</span> @schemaName <span style="color: #808080;">+</span> N<span style="color: #FF0000;">'.'</span> <span style="color: #808080;">+</span> @objectName <span style="color: #808080;">+</span> N<span style="color: #FF0000;">' ReOrganize'</span>;
&nbsp;
            <span style="color: #008080;">/* If our index is partitioned, we should always reorganize */</span>
            <span style="color: #0000FF;">IF</span> @partitionCount <span style="color: #808080;">&gt;</span> <span style="color: #000;">1</span>
                <span style="color: #0000FF;">SET</span> @sqlCommand <span style="color: #808080;">=</span> @sqlCommand <span style="color: #808080;">+</span> N<span style="color: #FF0000;">' Partition = '</span> 
                                <span style="color: #808080;">+</span> <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span>@partitionNumber <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">10</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span>;
&nbsp;
        <span style="color: #0000FF;">END</span>;
&nbsp;
        <span style="color: #008080;">/* If the index is heavily fragmented and doesn't contain any partitions or LOB's, rebuild it */</span>
        <span style="color: #0000FF;">IF</span> @fragmentation <span style="color: #808080;">&gt;=</span> @rebuildThreshold And IsNull<span style="color: #808080;">&#40;</span>@containsLOB, <span style="color: #000;">0</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">!=</span> <span style="color: #000;">1</span> And @partitionCount <span style="color: #808080;">&lt;=</span> <span style="color: #000;">1</span>
        <span style="color: #0000FF;">BEGIN</span>
&nbsp;
            <span style="color: #008080;">/* Set online rebuild options; requires Enterprise Edition */</span>
            <span style="color: #0000FF;">IF</span> @onlineRebuild <span style="color: #808080;">=</span> <span style="color: #000;">1</span> And @editionCheck <span style="color: #808080;">=</span> <span style="color: #000;">1</span> 
                <span style="color: #0000FF;">SET</span> @rebuildCommand <span style="color: #808080;">=</span> N<span style="color: #FF0000;">' Rebuild With (Online = On'</span>;
            <span style="color: #0000FF;">ELSE</span>
                <span style="color: #0000FF;">SET</span> @rebuildCommand <span style="color: #808080;">=</span> N<span style="color: #FF0000;">' Rebuild With (Online = Off'</span>;
&nbsp;
            <span style="color: #008080;">/* Set processor restriction options; requires Enterprise Edition */</span>
            <span style="color: #0000FF;">IF</span> @maxDopRestriction <span style="color: #0000FF;">IS</span> Not Null And @editionCheck <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
                <span style="color: #0000FF;">SET</span> @rebuildCommand <span style="color: #808080;">=</span> @rebuildCommand <span style="color: #808080;">+</span> N<span style="color: #FF0000;">', MaxDop = '</span> <span style="color: #808080;">+</span> <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span>@maxDopRestriction <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">2</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">+</span> N<span style="color: #FF0000;">')'</span>;
            <span style="color: #0000FF;">ELSE</span>
                <span style="color: #0000FF;">SET</span> @rebuildCommand <span style="color: #808080;">=</span> @rebuildCommand <span style="color: #808080;">+</span> N<span style="color: #FF0000;">')'</span>;
&nbsp;
            <span style="color: #0000FF;">SET</span> @sqlCommand <span style="color: #808080;">=</span> N<span style="color: #FF0000;">'Alter Index '</span> <span style="color: #808080;">+</span> @indexName <span style="color: #808080;">+</span> N<span style="color: #FF0000;">' On '</span> <span style="color: #808080;">+</span> @databaseName <span style="color: #808080;">+</span> N<span style="color: #FF0000;">'.'</span>
                            <span style="color: #808080;">+</span> @schemaName <span style="color: #808080;">+</span> N<span style="color: #FF0000;">'.'</span> <span style="color: #808080;">+</span> @objectName <span style="color: #808080;">+</span> @rebuildCommand;
&nbsp;
        <span style="color: #0000FF;">END</span>;
&nbsp;
        <span style="color: #008080;">/* Are we executing the SQL?  If so, do it */</span>
        <span style="color: #0000FF;">IF</span> @executeSQL <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
        <span style="color: #0000FF;">BEGIN</span>
&nbsp;
            <span style="color: #0000FF;">IF</span> @debugMode <span style="color: #808080;">=</span> <span style="color: #000;">1</span> <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'  Executing SQL statements...'</span>, <span style="color: #000;">0</span>, <span style="color: #000;">42</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">WITH</span> NoWait;
&nbsp;
            <span style="color: #008080;">/* Grab the time for logging purposes */</span>
            <span style="color: #0000FF;">SET</span> @dateTimeStart  <span style="color: #808080;">=</span> <span style="color: #FF00FF;">GETDATE</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#41;</span>;
&nbsp;
            <span style="color: #008080;">/* Log our actions */</span>
            <span style="color: #0000FF;">INSERT</span> <span style="color: #0000FF;">INTO</span> dbo.<span style="color: #202020;">dba_indexDefragLog</span>
            <span style="color: #808080;">&#40;</span>
                  databaseID
                , databaseName
                , objectID
                , objectName
                , indexID
                , indexName
                , partitionNumber
                , fragmentation
                , page_count
                , dateTimeStart
            <span style="color: #808080;">&#41;</span>
            <span style="color: #0000FF;">SELECT</span>
                  @databaseID
                , @databaseName
                , @objectID
                , @objectName
                , @indexID
                , @indexName
                , @partitionNumber
                , @fragmentation
                , @pageCount
                , @dateTimeStart;
&nbsp;
            <span style="color: #0000FF;">SET</span> @indexDefrag_id <span style="color: #808080;">=</span> <span style="color: #FF00FF;">SCOPE_IDENTITY</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#41;</span>;
&nbsp;
            <span style="color: #008080;">/* Execute our defrag! */</span>
            <span style="color: #0000FF;">EXECUTE</span> <span style="color: #AF0000;">SP_EXECUTESQL</span> @sqlCommand;
            <span style="color: #0000FF;">SET</span> @dateTimeEnd  <span style="color: #808080;">=</span> <span style="color: #FF00FF;">GETDATE</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#41;</span>;
&nbsp;
            <span style="color: #008080;">/* Update our log with our completion time */</span>
            <span style="color: #0000FF;">UPDATE</span> dbo.<span style="color: #202020;">dba_indexDefragLog</span>
            <span style="color: #0000FF;">SET</span> dateTimeEnd <span style="color: #808080;">=</span> @dateTimeEnd
                , durationSeconds <span style="color: #808080;">=</span> <span style="color: #FF00FF;">DATEDIFF</span><span style="color: #808080;">&#40;</span><span style="color: #0000FF;">SECOND</span>, @dateTimeStart, @dateTimeEnd<span style="color: #808080;">&#41;</span>
            <span style="color: #0000FF;">WHERE</span> indexDefrag_id <span style="color: #808080;">=</span> @indexDefrag_id;
&nbsp;
            <span style="color: #008080;">/* Just a little breather for the server */</span>
            <span style="color: #0000FF;">WAITFOR</span> Delay @defragDelay;
&nbsp;
            <span style="color: #008080;">/* Print if specified to do so */</span>
            <span style="color: #0000FF;">IF</span> @printCommands <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
                <span style="color: #0000FF;">PRINT</span> N<span style="color: #FF0000;">'Executed: '</span> <span style="color: #808080;">+</span> @sqlCommand;
        <span style="color: #0000FF;">END</span>
        <span style="color: #0000FF;">ELSE</span>
        <span style="color: #008080;">/* Looks like we're not executing, just printing the commands */</span>
        <span style="color: #0000FF;">BEGIN</span>
            <span style="color: #0000FF;">IF</span> @debugMode <span style="color: #808080;">=</span> <span style="color: #000;">1</span> <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'  Printing SQL statements...'</span>, <span style="color: #000;">0</span>, <span style="color: #000;">42</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">WITH</span> NoWait;
&nbsp;
            <span style="color: #0000FF;">IF</span> @printCommands <span style="color: #808080;">=</span> <span style="color: #000;">1</span> <span style="color: #0000FF;">PRINT</span> IsNull<span style="color: #808080;">&#40;</span>@sqlCommand, <span style="color: #FF0000;">'error!'</span><span style="color: #808080;">&#41;</span>;
        <span style="color: #0000FF;">END</span>
&nbsp;
        <span style="color: #0000FF;">IF</span> @debugMode <span style="color: #808080;">=</span> <span style="color: #000;">1</span> <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'  Updating our index defrag status...'</span>, <span style="color: #000;">0</span>, <span style="color: #000;">42</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">WITH</span> NoWait;
&nbsp;
        <span style="color: #008080;">/* Update our index defrag list so we know we've finished with that index */</span>
        <span style="color: #0000FF;">UPDATE</span> #indexDefragList
        <span style="color: #0000FF;">SET</span> defragStatus <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
        <span style="color: #0000FF;">WHERE</span> databaseID       <span style="color: #808080;">=</span> @databaseID
          And objectID         <span style="color: #808080;">=</span> @objectID
          And indexID          <span style="color: #808080;">=</span> @indexID
          And partitionNumber  <span style="color: #808080;">=</span> @partitionNumber;
&nbsp;
    <span style="color: #0000FF;">END</span>
&nbsp;
    <span style="color: #008080;">/* Do we want to output our fragmentation results? */</span>
    <span style="color: #0000FF;">IF</span> @printFragmentation <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
    <span style="color: #0000FF;">BEGIN</span>
&nbsp;
        <span style="color: #0000FF;">IF</span> @debugMode <span style="color: #808080;">=</span> <span style="color: #000;">1</span> <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'  Displaying fragmentation results...'</span>, <span style="color: #000;">0</span>, <span style="color: #000;">42</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">WITH</span> NoWait;
&nbsp;
        <span style="color: #0000FF;">SELECT</span> databaseID
            , databaseName
            , objectID
            , objectName
            , indexID
            , indexName
            , fragmentation
            , page_count
        <span style="color: #0000FF;">FROM</span> #indexDefragList;
&nbsp;
    <span style="color: #0000FF;">END</span>;
&nbsp;
    <span style="color: #008080;">/* Do we want to rebuild stats? */</span>
    <span style="color: #0000FF;">IF</span> @rebuildStats <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
    <span style="color: #0000FF;">BEGIN</span>
&nbsp;
        <span style="color: #0000FF;">WHILE</span> Exists<span style="color: #808080;">&#40;</span><span style="color: #0000FF;">SELECT</span> <span style="color: #0000FF;">TOP</span> <span style="color: #000;">1</span> <span style="color: #808080;">*</span> <span style="color: #0000FF;">FROM</span> #databaseList <span style="color: #0000FF;">WHERE</span> statsStatus <span style="color: #808080;">=</span> <span style="color: #000;">0</span><span style="color: #808080;">&#41;</span>
        <span style="color: #0000FF;">BEGIN</span>
&nbsp;
            <span style="color: #008080;">/* Build our SQL statement to update stats */</span>
            <span style="color: #0000FF;">SELECT</span> <span style="color: #0000FF;">TOP</span> <span style="color: #000;">1</span> @rebuildStatsSQL <span style="color: #808080;">=</span> <span style="color: #FF0000;">'Use ['</span> <span style="color: #808080;">+</span> databaseName <span style="color: #808080;">+</span> <span style="color: #FF0000;">']; '</span> <span style="color: #808080;">+</span> 
                                            <span style="color: #FF0000;">'Execute sp_updatestats;'</span>
                    , @rebuildStatsID <span style="color: #808080;">=</span> databaseID
            <span style="color: #0000FF;">FROM</span> #databaseList
            <span style="color: #0000FF;">WHERE</span> statsStatus <span style="color: #808080;">=</span> <span style="color: #000;">0</span>;
&nbsp;
            <span style="color: #0000FF;">SET</span> @debugMessage <span style="color: #808080;">=</span> <span style="color: #FF0000;">'Rebuilding Statistics: '</span> <span style="color: #808080;">+</span> @rebuildStatsSQL;
&nbsp;
            <span style="color: #0000FF;">IF</span> @debugMode <span style="color: #808080;">=</span> <span style="color: #000;">1</span> <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span>@debugMessage, <span style="color: #000;">0</span>, <span style="color: #000;">42</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">WITH</span> NoWait;
&nbsp;
            <span style="color: #008080;">/* Execute our stats update! */</span>
            <span style="color: #0000FF;">EXECUTE</span> <span style="color: #AF0000;">SP_EXECUTESQL</span> @rebuildStatsSQL;
&nbsp;
            <span style="color: #008080;">/* Keep track of which databases have been updated */</span>
            <span style="color: #0000FF;">UPDATE</span> #databaseList 
            <span style="color: #0000FF;">SET</span> statsStatus <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
            <span style="color: #0000FF;">WHERE</span> databaseID <span style="color: #808080;">=</span> @rebuildStatsID;
&nbsp;
        <span style="color: #0000FF;">END</span>;
    <span style="color: #0000FF;">END</span>;
&nbsp;
    <span style="color: #008080;">/* When everything is said and done, make sure to get rid of our temp table */</span>
    <span style="color: #0000FF;">DROP</span> <span style="color: #0000FF;">TABLE</span> #indexDefragList;
    <span style="color: #0000FF;">DROP</span> <span style="color: #0000FF;">TABLE</span> #databaseList;
    <span style="color: #0000FF;">DROP</span> <span style="color: #0000FF;">TABLE</span> #processor;
&nbsp;
    <span style="color: #0000FF;">IF</span> @debugMode <span style="color: #808080;">=</span> <span style="color: #000;">1</span> <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'DONE!  Thank you for taking care of your indexes!  :)'</span>, <span style="color: #000;">0</span>, <span style="color: #000;">42</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">WITH</span> NoWait;
&nbsp;
    <span style="color: #0000FF;">SET</span> <span style="color: #0000FF;">NOCOUNT</span> <span style="color: #0000FF;">OFF</span>;
    <span style="color: #0000FF;">RETURN</span> <span style="color: #000;">0</span>
<span style="color: #0000FF;">END</span>
Go
&nbsp;
<span style="color: #0000FF;">SET</span> Quoted_Identifier <span style="color: #0000FF;">OFF</span> 
<span style="color: #0000FF;">SET</span> ANSI_Nulls <span style="color: #0000FF;">ON</span>
Go</pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://sqlfool.com/2009/06/index-defrag-script-v30/feed/</wfw:commentRss>
		<slash:comments>108</slash:comments>
		</item>
		<item>
		<title>Webcast Tomorrow!</title>
		<link>http://sqlfool.com/2009/05/webcast-tomorrow/</link>
		<comments>http://sqlfool.com/2009/05/webcast-tomorrow/#comments</comments>
		<pubDate>Wed, 27 May 2009 20:09:30 +0000</pubDate>
		<dc:creator>Michelle Ufford</dc:creator>
				<category><![CDATA[PASS]]></category>
		<category><![CDATA[Presentations]]></category>
		<category><![CDATA[SQL 2008]]></category>
		<category><![CDATA[SQL Tips]]></category>
		<category><![CDATA[Syndication]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[presentation]]></category>
		<category><![CDATA[SSMS]]></category>
		<category><![CDATA[webcast]]></category>

		<guid isPermaLink="false">http://sqlfool.com/?p=981</guid>
		<description><![CDATA[I'm excited to be doing a webcast tomorrow with the infamous illustrious Brent Ozar for Quest's Pain-of-the-Week. The title is "Getting Started with SQL Server Management Studio," and as you've probably gathered, it's pretty entry-level stuff. If you read my blog, then chances are you don't need to watch this webcast. But if you know [...]]]></description>
			<content:encoded><![CDATA[<p>I'm excited to be doing a webcast tomorrow with the <span style="text-decoration: line-through;">infamous</span> illustrious <a href="http://www.brentozar.com" target="_blank">Brent Ozar</a> for <a href="http://www.quest.com/backstage/pow.aspx" target="_blank">Quest's Pain-of-the-Week</a>.  The title is "<a href="http://www.quest.com/events/listdetails.aspx?contentid=9602&amp;technology=&amp;prod=&amp;prodfamily=&amp;loc" target="_blank">Getting Started with SQL Server Management Studio</a>," and as you've probably gathered, it's pretty entry-level stuff.  If you read my blog, then chances are you don't need to watch this webcast.  But if you know anyone who's trying to learn SQL Server or is trying to make the upgrade from 2000 to 2005/2008, this may be a good webcast for them.</p>
<p>I've also got a few other speaking engagements coming up:</p>
<p>June 2nd: <a href="http://www.cvineta.org/" target="_blank">Cedar Valley .NET User Group</a><br />
I'll be reprising my Iowa Code Camp presentation on "SQL Server for the .NET Developer" for CVINETA.  This presentation focuses on what you need to know about good table design, indexing strategies, and fragmentation... you know, what you wish every .NET developer knew about SQL Server.  <img src='http://sqlfool.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>June 11th: <a href="http://www.quest.com/events/listdetails.aspx?contentid=9601&amp;technology=&amp;prod=&amp;prodfamily=&amp;loc=" target="_blank">PoTW: Time-Saving SQL Server Management Studio Tips &amp; Tricks</a><br />
I'll also be doing this webcast with <a href="http://twitter.com/BrentO" target="_blank">@BrentO</a> as a follow-up to our webcast tomorrow.  It will focus on how to save time and improve your sanity by using some neat little tricks in SSMS 2008.</p>
]]></content:encoded>
			<wfw:commentRss>http://sqlfool.com/2009/05/webcast-tomorrow/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>BOL 2008 Update Released</title>
		<link>http://sqlfool.com/2009/05/bol-2008update-released/</link>
		<comments>http://sqlfool.com/2009/05/bol-2008update-released/#comments</comments>
		<pubDate>Fri, 22 May 2009 21:39:22 +0000</pubDate>
		<dc:creator>Michelle Ufford</dc:creator>
				<category><![CDATA[SQL 2008]]></category>
		<category><![CDATA[Syndication]]></category>
		<category><![CDATA[2008]]></category>
		<category><![CDATA[BOL]]></category>
		<category><![CDATA[books online]]></category>
		<category><![CDATA[SSMS]]></category>

		<guid isPermaLink="false">http://sqlfool.com/?p=975</guid>
		<description><![CDATA[If you haven't heard, Microsoft released an update to Books Online for SQL Server 2008 yesterday. You can find the download here: http://www.microsoft.com/downloads/details.aspx?FamilyID=765433f7-0983-4d7a-b628-0a98145bcb97&#038;displaylang=en]]></description>
			<content:encoded><![CDATA[<p>If you haven't heard, Microsoft released an update to Books Online for SQL Server 2008 yesterday.  You can find the download here:</p>
<p><a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=765433f7-0983-4d7a-b628-0a98145bcb97&#038;displaylang=en" target="_blank">http://www.microsoft.com/downloads/details.aspx?FamilyID=765433f7-0983-4d7a-b628-0a98145bcb97&#038;displaylang=en</a></p>
]]></content:encoded>
			<wfw:commentRss>http://sqlfool.com/2009/05/bol-2008update-released/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Overhead in Non-Unique Clustered Indexes</title>
		<link>http://sqlfool.com/2009/05/overhead-i-non-unique-clustered-indexes/</link>
		<comments>http://sqlfool.com/2009/05/overhead-i-non-unique-clustered-indexes/#comments</comments>
		<pubDate>Thu, 21 May 2009 13:22:29 +0000</pubDate>
		<dc:creator>Michelle Ufford</dc:creator>
				<category><![CDATA[Internals]]></category>
		<category><![CDATA[Performance & Tuning]]></category>
		<category><![CDATA[SQL 2008]]></category>
		<category><![CDATA[Syndication]]></category>
		<category><![CDATA[indexes]]></category>
		<category><![CDATA[performance]]></category>

		<guid isPermaLink="false">http://sqlfool.com/?p=961</guid>
		<description><![CDATA[I've received a couple of questions regarding my article, Performance Considerations of Data Types, and the overhead associated with non-unique clustered indexes. I started to respond via e-mail, but my response was so long I decided to turn it into a blog post instead. I should start by clarifying that non-unique clustered indexes do not [...]]]></description>
			<content:encoded><![CDATA[<p>I've received a couple of questions regarding my article, <a href="http://sqlfool.com/2009/05/performance-considerations-of-data-types/" target="_blank">Performance Considerations of Data Types</a>, and the overhead associated with non-unique clustered indexes.  I started to respond via e-mail, but my response was so long I decided to turn it into a blog post instead.  <img src='http://sqlfool.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>I should start by clarifying that <strong>non-unique clustered indexes do not necessarily consume more space and overhead</strong>; it depends on the data stored.  If you have duplicate clustered key values, the first instance of the value will be handled as though it were unique.  Any subsequent values, however, will incur overhead to manage the uniquifier that SQL Server adds to maintain row uniqueness.  This same overhead is also incurred in non-clustered indexes, too, adding to the overall expense of this approach.</p>
<p>I think it helps to actually look at the data, so let's walk through a few different common scenarios.  We'll create a table with a unique clustered index, a table with a non-unique clustered index but no duplicates, and a table with duplicate key values.  </p>
<p>Also, a little warning that I started to write this in SQL Server 2008, and since I'm on a 2008 kick, I decided to leave it that way.  You can modify this pretty easily to work in 2005, if necessary.</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">USE</span> sandbox;
Go
&nbsp;
<span style="color: #008080;">/* Unique, clustered index, no duplicate values */</span>
<span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">TABLE</span> dbo.<span style="color: #202020;">uniqueClustered</span>
<span style="color: #808080;">&#40;</span>
      myDate    <span style="color: #0000FF;">DATE</span>        Not Null
    , myNumber  <span style="color: #0000FF;">INT</span>         Not Null
    , myColumn  <span style="color: #0000FF;">CHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">995</span><span style="color: #808080;">&#41;</span>   Not Null
<span style="color: #808080;">&#41;</span>;
&nbsp;
<span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">UNIQUE</span> <span style="color: #0000FF;">CLUSTERED</span> <span style="color: #0000FF;">INDEX</span> CIX_uniqueClustered
    <span style="color: #0000FF;">ON</span> dbo.<span style="color: #202020;">uniqueClustered</span><span style="color: #808080;">&#40;</span>myDate<span style="color: #808080;">&#41;</span>;
&nbsp;
&nbsp;
<span style="color: #008080;">/* Non-unique clustered index, but no duplicate values */</span>
<span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">TABLE</span> dbo.<span style="color: #202020;">nonUniqueNoDups</span>
<span style="color: #808080;">&#40;</span>
      myDate    <span style="color: #0000FF;">DATE</span>        Not Null
    , myNumber  <span style="color: #0000FF;">INT</span>         Not Null
    , myColumn  <span style="color: #0000FF;">CHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">995</span><span style="color: #808080;">&#41;</span>   Not Null
<span style="color: #808080;">&#41;</span>;
&nbsp;
<span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">CLUSTERED</span> <span style="color: #0000FF;">INDEX</span> CIX_nonUniqueNoDups
    <span style="color: #0000FF;">ON</span> dbo.<span style="color: #202020;">nonUniqueNoDups</span><span style="color: #808080;">&#40;</span>myDate<span style="color: #808080;">&#41;</span>;
&nbsp;
&nbsp;
<span style="color: #008080;">/* Non-unique clustered index, duplicate values */</span>
<span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">TABLE</span> dbo.<span style="color: #202020;">nonUniqueDuplicates</span>
<span style="color: #808080;">&#40;</span>
      myDate    <span style="color: #0000FF;">DATE</span>        Not Null
    , myNumber  <span style="color: #0000FF;">INT</span>         Not Null
    , myColumn  <span style="color: #0000FF;">CHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">995</span><span style="color: #808080;">&#41;</span>   Not Null
<span style="color: #808080;">&#41;</span>;
&nbsp;
<span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">CLUSTERED</span> <span style="color: #0000FF;">INDEX</span> CIX_nonUniqueDuplicates
    <span style="color: #0000FF;">ON</span> dbo.<span style="color: #202020;">nonUniqueDuplicates</span><span style="color: #808080;">&#40;</span>myDate<span style="color: #808080;">&#41;</span>;</pre></div></div>

<p>I'm going to use the <a href="http://msdn.microsoft.com/en-us/library/bb630352.aspx" target="_blank">date</a> data type in 2008 for my clustered index key.  To ensure uniqueness for the first two tables, I'll iterate through a few years' worth of dates.  This is typical of what you may see in a data mart, where you'd have one record with an aggregation of each day's data.  For the table with duplicate values, I'm going to insert the same date for each row.</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #008080;">/* Populate some test data */</span>
<span style="color: #0000FF;">SET</span> <span style="color: #0000FF;">NOCOUNT</span> <span style="color: #0000FF;">ON</span>;
<span style="color: #0000FF;">DECLARE</span> @myDate <span style="color: #0000FF;">DATE</span> <span style="color: #808080;">=</span> <span style="color: #FF0000;">'1990-01-01'</span>
    , @myNumber <span style="color: #0000FF;">INT</span> <span style="color: #808080;">=</span> <span style="color: #000;">1</span>;
&nbsp;
<span style="color: #0000FF;">WHILE</span> @myDate <span style="color: #808080;">&lt;</span> <span style="color: #FF0000;">'2010-01-01'</span>
<span style="color: #0000FF;">BEGIN</span>
&nbsp;
    <span style="color: #0000FF;">INSERT</span> <span style="color: #0000FF;">INTO</span> dbo.<span style="color: #202020;">uniqueClustered</span>
    <span style="color: #0000FF;">SELECT</span> @myDate, @myNumber, <span style="color: #FF0000;">'data'</span>;
&nbsp;
    <span style="color: #0000FF;">INSERT</span> <span style="color: #0000FF;">INTO</span> dbo.<span style="color: #202020;">nonUniqueNoDups</span>
    <span style="color: #0000FF;">SELECT</span> @myDate, @myNumber, <span style="color: #FF0000;">'data'</span>;
&nbsp;
    <span style="color: #0000FF;">INSERT</span> <span style="color: #0000FF;">INTO</span> dbo.<span style="color: #202020;">nonUniqueDuplicates</span>
    <span style="color: #0000FF;">SELECT</span> <span style="color: #FF0000;">'2009-01-01'</span>, @myNumber, <span style="color: #FF0000;">'data'</span>;
&nbsp;
    <span style="color: #0000FF;">SELECT</span> @myDate <span style="color: #808080;">=</span> <span style="color: #FF00FF;">DATEADD</span><span style="color: #808080;">&#40;</span><span style="color: #0000FF;">DAY</span>, <span style="color: #000;">1</span>, @myDate<span style="color: #808080;">&#41;</span>
        , @myNumber <span style="color: #808080;">+=</span> <span style="color: #000;">1</span>;
&nbsp;
<span style="color: #0000FF;">END</span>;</pre></div></div>

<p>After running the above script, each table should have 7,305 records.  This is obviously pretty small for a table, but it'll serve our purposes.  Now let's take a look at the size of our tables:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #008080;">/* Look at the details of our indexes */</span>
&nbsp;
<span style="color: #008080;">/* Unique, clustered index, no duplicate values */</span>
<span style="color: #0000FF;">SELECT</span> <span style="color: #FF0000;">'unique'</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'type'</span>, page_count, avg_page_space_used_in_percent, record_count
    , min_record_size_in_bytes, max_record_size_in_bytes
<span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">dm_db_index_physical_stats</span><span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">DB_ID</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#41;</span>, <span style="color: #FF00FF;">OBJECT_ID</span><span style="color: #808080;">&#40;</span>N<span style="color: #FF0000;">'uniqueClustered'</span><span style="color: #808080;">&#41;</span>, Null, Null, N<span style="color: #FF0000;">'Detailed'</span><span style="color: #808080;">&#41;</span> 
<span style="color: #0000FF;">WHERE</span> index_level <span style="color: #808080;">=</span> <span style="color: #000;">0</span>
<span style="color: #0000FF;">UNION</span> All
<span style="color: #008080;">/* Non-unique clustered index, but no duplicate values */</span>
<span style="color: #0000FF;">SELECT</span> <span style="color: #FF0000;">'non-unique, no dups'</span>, page_count, avg_page_space_used_in_percent, record_count
    , min_record_size_in_bytes, max_record_size_in_bytes
<span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">dm_db_index_physical_stats</span><span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">DB_ID</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#41;</span>, <span style="color: #FF00FF;">OBJECT_ID</span><span style="color: #808080;">&#40;</span>N<span style="color: #FF0000;">'nonUniqueNoDups'</span><span style="color: #808080;">&#41;</span>, Null, Null, N<span style="color: #FF0000;">'Detailed'</span><span style="color: #808080;">&#41;</span> 
<span style="color: #0000FF;">WHERE</span> index_level <span style="color: #808080;">=</span> <span style="color: #000;">0</span>
<span style="color: #0000FF;">UNION</span> All
<span style="color: #008080;">/* Non-unique clustered index, duplicate values */</span>
<span style="color: #0000FF;">SELECT</span> <span style="color: #FF0000;">'duplicates'</span>, page_count, avg_page_space_used_in_percent, record_count
    , min_record_size_in_bytes, max_record_size_in_bytes
<span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">dm_db_index_physical_stats</span><span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">DB_ID</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#41;</span>, <span style="color: #FF00FF;">OBJECT_ID</span><span style="color: #808080;">&#40;</span>N<span style="color: #FF0000;">'nonUniqueDuplicates'</span><span style="color: #808080;">&#41;</span>, Null, Null, N<span style="color: #FF0000;">'Detailed'</span><span style="color: #808080;">&#41;</span> 
<span style="color: #0000FF;">WHERE</span> index_level <span style="color: #808080;">=</span> <span style="color: #000;">0</span>;</pre></div></div>

<p>Here's the results:</p>

<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">type                page_count           avg_page_space_used_in_percent record_count         min_record_size_in_bytes max_record_size_in_bytes
------------------- -------------------- ------------------------------ -------------------- ------------------------ ------------------------
unique              914                  99.8055102545095               7305                 1009                     1009
non-unique, no dups 914                  99.8055102545095               7305                 1009                     1009
duplicates          1044                 88.066036570299                7305                 1009                     1017</pre></div></div>

<p>I want to point out a couple of things.  First, there is no difference in the number of pages between the non-unique clustered index with no duplicates ([nonUniqueNoDups]) and the unique clustered index ([uniqueClustered]).  The table with duplicate clustered key values, however, requires 14% more pages to store the same amount of data.  Secondly, the [max_record_size_in_bytes] of the [nonUniqueDuplicates] table is 8 bytes more than that of the other two.  We'll discuss why in a minute.  </p>
<p>Now let's take a look at the actual data pages.  For this, I'm going to use my <a href="http://sqlfool.com/2009/05/page-internals-investigation-proc/" target="_blank">page internals proc</a>.</p>

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;">Execute dbo<span style="color: #66cc66;">.</span>dba_viewPageData_sp
      @databaseName <span style="color: #66cc66;">=</span> <span style="color: #ff0000;">'sandbox'</span>
    <span style="color: #66cc66;">,</span> @tableName    <span style="color: #66cc66;">=</span> <span style="color: #ff0000;">'sandbox.dbo.uniqueClustered'</span>
    <span style="color: #66cc66;">,</span> @indexName    <span style="color: #66cc66;">=</span> <span style="color: #ff0000;">'CIX_uniqueClustered'</span>;</pre></div></div>

<p>I'm not going to post the entire results here, but I want to draw your attention to "m_slotCnt = 8", which is near the top of the page.  That means 8 records are stored on this page.  Also, when you look near the end of the first record (Slot 0), you should see the following results:</p>

<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">Slot 0 Offset 0x60 Length 1009
Record Type = PRIMARY_RECORD         Record Attributes =  NULL_BITMAP     Record Size = 1009
Memory Dump @0x00A9C060
00000000:   1000ee03 c3150b01 00000064 61746120 †..î.Ã......data 
[...]
000003F0:   00†††††††††††††††††††††††††††††††††††.  
&nbsp;
Slot 0 Column 1 Offset 0x4 Length 3 Length (physical) 3
myDate = 1990-01-01                  
&nbsp;
Slot 0 Column 2 Offset 0x7 Length 4 Length (physical) 4
myNumber = 1                         
&nbsp;
Slot 0 Column 3 Offset 0xb Length 995 Length (physical) 995
myColumn = data</pre></div></div>

<p>Now let's look at the table that has a non-unique clustered index but no duplicates:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">EXECUTE</span> dbo.<span style="color: #202020;">dba_viewPageData_sp</span>
      @databaseName <span style="color: #808080;">=</span> <span style="color: #FF0000;">'sandbox'</span>
    , @tableName    <span style="color: #808080;">=</span> <span style="color: #FF0000;">'sandbox.dbo.nonUniqueNoDups'</span>
    , @indexName    <span style="color: #808080;">=</span> <span style="color: #FF0000;">'CIX_nonUniqueNoDups'</span>;</pre></div></div>

<p>The m_slotCnt count is also 8 for this page.  This time, let's glance at the first and second records (Slot 0 and 1 respectively):</p>

<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">Slot 0 Offset 0x60 Length 1009
Record Type = PRIMARY_RECORD         Record Attributes =  NULL_BITMAP     Record Size = 1009
Memory Dump @0x62FDC060
00000000:   1000ee03 c3150b01 00000064 61746120 †..î.Ã......data    
[...]
000003F0:   00†††††††††††††††††††††††††††††††††††.                        
&nbsp;
Slot 0 Column 0 Offset 0x0 Length 4 Length (physical) 0
UNIQUIFIER = 0                       
&nbsp;
Slot 0 Column 1 Offset 0x4 Length 3 Length (physical) 3
myDate = 1990-01-01                  
&nbsp;
Slot 0 Column 2 Offset 0x7 Length 4 Length (physical) 4
myNumber = 1                         
&nbsp;
Slot 0 Column 3 Offset 0xb Length 995 Length (physical) 995
myColumn = data
&nbsp;
&nbsp;
Slot 1 Offset 0x451 Length 1009
Record Type = PRIMARY_RECORD         Record Attributes =  NULL_BITMAP     Record Size = 1009
Memory Dump @0x62FDC451
&nbsp;
00000000:   1000ee03 c4150b02 00000064 61746120 †..î.Ä......data          
[...]
000003F0:   00†††††††††††††††††††††††††††††††††††.                        
&nbsp;
Slot 1 Column 0 Offset 0x0 Length 4 Length (physical) 0
UNIQUIFIER = 0                       
&nbsp;
Slot 1 Column 1 Offset 0x4 Length 3 Length (physical) 3
myDate = 1990-01-02                  
&nbsp;
Slot 1 Column 2 Offset 0x7 Length 4 Length (physical) 4
myNumber = 2                         
&nbsp;
Slot 1 Column 3 Offset 0xb Length 995 Length (physical) 995
myColumn = data</pre></div></div>

<p>We now see a new addition to the row, "UNIQUIFIER = 0."  This is SQL Server's way of managing row uniqueness internally.  You'll notice that, because the clustered key values are unique, the UNIQUIFIER is set to 0 and the row size is still 1009; for all intents and purposes, the UNIQUIFIER is not consuming any space.</p>
<p><strong>Update:</strong>  The DBCC God himself, <a href="http://www.sqlskills.com/blogs/paul/" target="_blank">Paul Randal</a>, explained that non-dupes actually have a NULL UNIQUIFIER, which DBCC PAGE displays as a 0.  Thanks for explaining, Paul!  I wondered about that but chalked it up to SQL voodoo.  </p>
<p>Now let's look at our final case, a non-unique clustered index with duplicate key values:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">EXECUTE</span> dbo.<span style="color: #202020;">dba_viewPageData_sp</span>
      @databaseName <span style="color: #808080;">=</span> <span style="color: #FF0000;">'sandbox'</span>
    , @tableName    <span style="color: #808080;">=</span> <span style="color: #FF0000;">'sandbox.dbo.nonUniqueDuplicates'</span>
    , @indexName    <span style="color: #808080;">=</span> <span style="color: #FF0000;">'CIX_nonUniqueDuplicates'</span>;</pre></div></div>

<p>Here's where things get interesting.  The m_slotCnt value is now 7, which means we're now storing 1 record less per page.  Let's look at the details:</p>

<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">Slot 0 Offset 0x60 Length 1009
Record Type = PRIMARY_RECORD         Record Attributes =  NULL_BITMAP     Record Size = 1009
Memory Dump @0x00A9C060
00000000:   1000ee03 df300b01 00000064 61746120 †..î.ß0.....data  
[...]
000003F0:   00†††††††††††††††††††††††††††††††††††.                        
&nbsp;
Slot 0 Column 0 Offset 0x0 Length 4 Length (physical) 0
UNIQUIFIER = 0                       
&nbsp;
Slot 0 Column 1 Offset 0x4 Length 3 Length (physical) 3
myDate = 2009-01-01                  
&nbsp;
Slot 0 Column 2 Offset 0x7 Length 4 Length (physical) 4
myNumber = 1                         
&nbsp;
Slot 0 Column 3 Offset 0xb Length 995 Length (physical) 995
myColumn = data
&nbsp;
&nbsp;
Slot 1 Offset 0x451 Length 1017
&nbsp;
Record Type = PRIMARY_RECORD         Record Attributes =  NULL_BITMAP VARIABLE_COLUMNS
Record Size = 1017                   
Memory Dump @0x00A9C451
00000000:   3000ee03 df300b02 00000064 61746120 †0.î.ß0.....data  
[...]
000003F0:   000100f9 03010000 00†††††††††††††††††...ù.....                
&nbsp;
Slot 1 Column 0 Offset 0x3f5 Length 4 Length (physical) 4
UNIQUIFIER = 1                       
&nbsp;
Slot 1 Column 1 Offset 0x4 Length 3 Length (physical) 3
myDate = 2009-01-01                  
&nbsp;
Slot 1 Column 2 Offset 0x7 Length 4 Length (physical) 4
myNumber = 2                         
&nbsp;
Slot 1 Column 3 Offset 0xb Length 995 Length (physical) 995
myColumn = data</pre></div></div>

<p>The first record, Slot 0, looks exactly the same as in the previous table; the UNIQUIFIER is 0 and the row size is 1009.  The second record (Slot 1), however, now has a UNIQUIFIER value of 1 and the row size is 1017.  If you notice, the "Record Attributes" of Slot 1 are also different, with the addition of "VARIABLE_COLUMNS."  This is because the UNIQUIFIER is stored as a variable column.  The extra 8 bytes of overhead break down to 4 bytes to store the UNIQUIFIER, 2 bytes to store the variable column offset, and 2 bytes to store the variable count.  The tables we created used all fixed-length columns; you may notice some minor overhead differences if your table already contains variable columns.</p>
<p>To summarize, there is indeed a difference in the page structure between a unique clustered index and a non-unique clustered index; however, there's only a possible performance and space impact when storing duplicate clustered key values.  So there you go, more detail than you ever wanted to know about clustered indexes and uniqueness!</p>
]]></content:encoded>
			<wfw:commentRss>http://sqlfool.com/2009/05/overhead-i-non-unique-clustered-indexes/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Filtered Indexes: What You Need To Know</title>
		<link>http://sqlfool.com/2009/04/filtered-indexes-what-you-need-to-know/</link>
		<comments>http://sqlfool.com/2009/04/filtered-indexes-what-you-need-to-know/#comments</comments>
		<pubDate>Mon, 20 Apr 2009 17:32:56 +0000</pubDate>
		<dc:creator>Michelle Ufford</dc:creator>
				<category><![CDATA[Performance & Tuning]]></category>
		<category><![CDATA[SQL 2008]]></category>
		<category><![CDATA[Syndication]]></category>
		<category><![CDATA[2008]]></category>
		<category><![CDATA[filtered indexes]]></category>
		<category><![CDATA[indexes]]></category>

		<guid isPermaLink="false">http://sqlfool.com/?p=831</guid>
		<description><![CDATA[Filtered indexes are probably my favorite feature in 2008. That's saying a lot, since there are so many great new features to choose from. In this post, I want to explore a little about how filtered indexes work, how they can be applied, and some of the "gotchas" to be aware of. First, for those [...]]]></description>
			<content:encoded><![CDATA[<p>Filtered indexes are probably my favorite feature in 2008.  That's saying a lot, since there are so many great new features to choose from.  In this post, I want to explore a little about how filtered indexes work, how they can be applied, and some of the "gotchas" to be aware of.</p>
<p>First, for those of you who may not yet know about filtered indexes, allow me enlighten you.  In short, filtered indexes allow you to create an index on a subset of data using a filtering predicate.  Filters can only be applied to non-clustered indexes.  The general syntax of a filtered index is:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">NONCLUSTERED</span> <span style="color: #0000FF;">INDEX</span> <span style="color: #808080;">&#91;</span>index_name<span style="color: #808080;">&#93;</span>
<span style="color: #0000FF;">ON</span> <span style="color: #808080;">&#91;</span>table_name<span style="color: #808080;">&#93;</span> <span style="color: #808080;">&#40;</span><span style="color: #808080;">&#91;</span>column_list<span style="color: #808080;">&#93;</span><span style="color: #808080;">&#41;</span>
Include <span style="color: #808080;">&#40;</span><span style="color: #808080;">&#91;</span>column_list<span style="color: #808080;">&#93;</span><span style="color: #808080;">&#41;</span>
<span style="color: #0000FF;">WHERE</span> <span style="color: #808080;">&#91;</span>filtered_criteria<span style="color: #808080;">&#93;</span>;</pre></div></div>

<p>For our purposes, we're going to be working with the Sales.SalesOrderDetail table in the AdventureWorks database.  Let's look at a specific example.  Suppose we have a query that regularly searches on the [SpecialOfferID] column.</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">SELECT</span> SalesOrderID
    , <span style="color: #FF00FF;">COUNT</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">*</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'CountOfLineItem'</span>
    , <span style="color: #FF00FF;">SUM</span><span style="color: #808080;">&#40;</span>LineTotal<span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'SumOfLineTotal'</span>
<span style="color: #0000FF;">FROM</span> Sales.<span style="color: #202020;">SalesOrderDetail</span>
<span style="color: #0000FF;">WHERE</span> SpecialOfferID <span style="color: #808080;">&lt;&gt;</span> <span style="color: #000;">1</span>
<span style="color: #0000FF;">GROUP</span> <span style="color: #0000FF;">BY</span> SalesOrderID;</pre></div></div>

<p>We notice that there's no covering index for this query by looking at the actual execution plan:</p>
<div id="attachment_842" class="wp-caption alignnone" style="width: 310px"><a href="http://sqlfool.com/wp-content/uploads/2009/04/queryplan1.jpg"><img src="http://sqlfool.com/wp-content/uploads/2009/04/queryplan1-300x133.jpg" alt="Query Plan - Clustered Scan" title="queryplan1" width="300" height="133" class="size-medium wp-image-842" /></a><p class="wp-caption-text">Query Plan - Clustered Scan</p></div>
<p>If this is a commonly executed query, then we'd probably want to toss an index on it.  Before we get started, let's take a look at what the distribution of values are on that column:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">SELECT</span> SpecialOfferID
    , <span style="color: #FF00FF;">COUNT</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">*</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'rows'</span>
<span style="color: #0000FF;">FROM</span> Sales.<span style="color: #202020;">SalesOrderDetail</span>
<span style="color: #0000FF;">GROUP</span> <span style="color: #0000FF;">BY</span> SpecialOfferID
<span style="color: #0000FF;">ORDER</span> <span style="color: #0000FF;">BY</span> <span style="color: #FF00FF;">COUNT</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">*</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">DESC</span>;</pre></div></div>

<p>Our distribution of values is:</p>

<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">SpecialOfferID rows
-------------- -----------
1              115884
2              3428
3              606
13             524
14             244
16             169
7              137
8              98
11             84
4              80
9              61
5              2</pre></div></div>

<p>As you can see, [SpecialOfferID] = 1 accounts for 96% of our values.  In 2005, we'd create an index that may look something like this:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">NONCLUSTERED</span> <span style="color: #0000FF;">INDEX</span> IX_Sales_SalesOrderDetail_SpecialOfferID
    <span style="color: #0000FF;">ON</span> Sales.<span style="color: #202020;">SalesOrderDetail</span><span style="color: #808080;">&#40;</span>SpecialOfferID<span style="color: #808080;">&#41;</span>
    Include <span style="color: #808080;">&#40;</span>SalesOrderID, LineTotal<span style="color: #808080;">&#41;</span>;</pre></div></div>

<p>Now if we re-run our original query, this is what we see:</p>
<div id="attachment_836" class="wp-caption alignnone" style="width: 310px"><a href="http://sqlfool.com/wp-content/uploads/2009/04/queryplan2.jpg"><img src="http://sqlfool.com/wp-content/uploads/2009/04/queryplan2-300x160.jpg" alt="Indexed Query Plan" title="queryplan2" width="300" height="160" class="size-medium wp-image-836" /></a><p class="wp-caption-text">Indexed Query Plan</p></div>
<p>So we're now performing a non-clustered index seek instead of a clustered index scan.  Already this results in some pretty significant performance improvements.  To see this, we're going to use the <a href="http://msdn.microsoft.com/en-us/library/ms181714.aspx" target="_blank">INDEX query hint</a> to force an index scan.  We're also going to use the DBCC command <a href="http://msdn.microsoft.com/en-us/library/ms187762.aspx" target="_blank">DROPCLEANBUFFERS</a>, which will allow us to clear the buffer cache and better examine what's happening with our IO.</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">SET</span> <span style="color: #0000FF;">STATISTICS</span> IO <span style="color: #0000FF;">ON</span>;
&nbsp;
<span style="color: #0000FF;">DBCC</span> DropCleanBuffers;
&nbsp;
<span style="color: #0000FF;">SELECT</span> SalesOrderID
    , <span style="color: #FF00FF;">COUNT</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">*</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'CountOfLineItem'</span>
    , <span style="color: #FF00FF;">SUM</span><span style="color: #808080;">&#40;</span>LineTotal<span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'SumOfLineTotal'</span>
<span style="color: #0000FF;">FROM</span> Sales.<span style="color: #202020;">SalesOrderDetail</span> <span style="color: #0000FF;">WITH</span> 
    <span style="color: #808080;">&#40;</span><span style="color: #0000FF;">INDEX</span><span style="color: #808080;">&#40;</span>PK_SalesOrderDetail_SalesOrderID_SalesOrderDetailID<span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span>
<span style="color: #0000FF;">WHERE</span> SpecialOfferID <span style="color: #808080;">&lt;&gt;</span> <span style="color: #000;">1</span>
<span style="color: #0000FF;">GROUP</span> <span style="color: #0000FF;">BY</span> SalesOrderID;
&nbsp;
<span style="color: #0000FF;">DBCC</span> DropCleanBuffers;
&nbsp;
<span style="color: #0000FF;">SELECT</span> SalesOrderID
    , <span style="color: #FF00FF;">COUNT</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">*</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'CountOfLineItem'</span>
    , <span style="color: #FF00FF;">SUM</span><span style="color: #808080;">&#40;</span>LineTotal<span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'SumOfLineTotal'</span>
<span style="color: #0000FF;">FROM</span> Sales.<span style="color: #202020;">SalesOrderDetail</span>
<span style="color: #0000FF;">WHERE</span> SpecialOfferID <span style="color: #808080;">&lt;&gt;</span> <span style="color: #000;">1</span>
<span style="color: #0000FF;">GROUP</span> <span style="color: #0000FF;">BY</span> SalesOrderID;
&nbsp;
<span style="color: #0000FF;">SET</span> <span style="color: #0000FF;">STATISTICS</span> IO <span style="color: #0000FF;">OFF</span>;</pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">Clustered Index Scan:
Table 'SalesOrderDetail'. Scan count 1, logical reads 1240, physical reads 17, read-ahead reads 1242...
&nbsp;
NonClustered Index Seek:
Table 'SalesOrderDetail'. Scan count 2, logical reads 30, physical reads 4, read-ahead reads 480...</pre></div></div>

<p>As you can see, the non-clustered (NC) index seek performs quite a bit better.  Now let's create a filtered index and explore what happens:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">NONCLUSTERED</span> <span style="color: #0000FF;">INDEX</span> FIX_Sales_SalesOrderDetail_SpecialOfferID_Filtered
    <span style="color: #0000FF;">ON</span> Sales.<span style="color: #202020;">SalesOrderDetail</span><span style="color: #808080;">&#40;</span>SalesOrderID<span style="color: #808080;">&#41;</span>
    Include <span style="color: #808080;">&#40;</span>LineTotal<span style="color: #808080;">&#41;</span>
    <span style="color: #0000FF;">WHERE</span> SpecialOfferID <span style="color: #808080;">&lt;&gt;</span> <span style="color: #000;">1</span>;</pre></div></div>

<p>First, let's look at the pages consumed by each index:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">SELECT</span> i.<span style="color: #202020;">name</span>, ddips.<span style="color: #202020;">index_depth</span>, ddips.<span style="color: #202020;">index_level</span>
    , ddips.<span style="color: #202020;">page_count</span>, ddips.<span style="color: #202020;">record_count</span>
<span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">indexes</span> <span style="color: #0000FF;">AS</span> i
Join sys.<span style="color: #202020;">dm_db_index_physical_stats</span><span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">DB_ID</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#41;</span>, 
    <span style="color: #FF00FF;">OBJECT_ID</span><span style="color: #808080;">&#40;</span>N<span style="color: #FF0000;">'Sales.SalesOrderDetail'</span><span style="color: #808080;">&#41;</span>, Null, Null, N<span style="color: #FF0000;">'Detailed'</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> ddips
    <span style="color: #0000FF;">ON</span> i.<span style="color: #FF00FF;">OBJECT_ID</span> <span style="color: #808080;">=</span> ddips.<span style="color: #FF00FF;">OBJECT_ID</span>
    And i.<span style="color: #202020;">index_id</span> <span style="color: #808080;">=</span> ddips.<span style="color: #202020;">index_id</span>
<span style="color: #0000FF;">WHERE</span> i.<span style="color: #202020;">name</span> In <span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'IX_Sales_SalesOrderDetail_SpecialOfferID'</span>
    , <span style="color: #FF0000;">'FIX_Sales_SalesOrderDetail_SpecialOfferID_Filtered'</span>
    , <span style="color: #FF0000;">'PK_SalesOrderDetail_SalesOrderID_SalesOrderDetailID'</span><span style="color: #808080;">&#41;</span>
    <span style="color: #808080;">AND</span> ddips.<span style="color: #202020;">index_level</span> <span style="color: #808080;">=</span> <span style="color: #000;">0</span>;</pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">name                                                       index_depth index_level page_count  record_count
---------------------------------------------------------- ----------- ----------- ----------- --------------------
PK_SalesOrderDetail_SalesOrderID_SalesOrderDetailID        3           0           1234        121317
IX_Sales_SalesOrderDetail_SpecialOfferID                   3           0           480         121317
FIX_Sales_SalesOrderDetail_SpecialOfferID_Filtered         2           0           19          5433</pre></div></div>

<p>If you scroll over, you'll see that the clustered index consumes the most pages, naturally.  The non-filtered NC index consumes less pages than the clustered index because it's narrower; however, it still consumes more pages than the filtered index because it's storing every data row.  The filtered index, with only 5433 rows stored, is by far our smallest index, consuming 96% less space than our non-filtered NC index.  </p>
<p>Because we're using less space to store this index, we should also see an equivalent performance boost.  Let's verify that this is the case:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">SET</span> <span style="color: #0000FF;">STATISTICS</span> IO <span style="color: #0000FF;">ON</span>;
&nbsp;
<span style="color: #0000FF;">DBCC</span> DropCleanBuffers;
&nbsp;
<span style="color: #0000FF;">SELECT</span> SalesOrderID
    , <span style="color: #FF00FF;">COUNT</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">*</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'CountOfLineItem'</span>
    , <span style="color: #FF00FF;">SUM</span><span style="color: #808080;">&#40;</span>LineTotal<span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'SumOfLineTotal'</span>
<span style="color: #0000FF;">FROM</span> Sales.<span style="color: #202020;">SalesOrderDetail</span> <span style="color: #0000FF;">WITH</span> <span style="color: #808080;">&#40;</span><span style="color: #0000FF;">INDEX</span><span style="color: #808080;">&#40;</span>IX_Sales_SalesOrderDetail_SpecialOfferID<span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span>
<span style="color: #0000FF;">WHERE</span> SpecialOfferID <span style="color: #808080;">&lt;&gt;</span> <span style="color: #000;">1</span>
<span style="color: #0000FF;">GROUP</span> <span style="color: #0000FF;">BY</span> SalesOrderID;
&nbsp;
<span style="color: #0000FF;">DBCC</span> DropCleanBuffers;
&nbsp;
<span style="color: #0000FF;">SELECT</span> SalesOrderID
    , <span style="color: #FF00FF;">COUNT</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">*</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'CountOfLineItem'</span>
    , <span style="color: #FF00FF;">SUM</span><span style="color: #808080;">&#40;</span>LineTotal<span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'SumOfLineTotal'</span>
<span style="color: #0000FF;">FROM</span> Sales.<span style="color: #202020;">SalesOrderDetail</span>
<span style="color: #0000FF;">WHERE</span> SpecialOfferID <span style="color: #808080;">&lt;&gt;</span> <span style="color: #000;">1</span>
<span style="color: #0000FF;">GROUP</span> <span style="color: #0000FF;">BY</span> SalesOrderID;
&nbsp;
<span style="color: #0000FF;">SET</span> <span style="color: #0000FF;">STATISTICS</span> IO <span style="color: #0000FF;">OFF</span>;</pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">NonClustered Index Seek:
Table 'SalesOrderDetail'. Scan count 2, logical reads 30, physical reads 4, read-ahead reads 480
&nbsp;
Filtered Index Scan:
Table 'SalesOrderDetail'. Scan count 1, logical reads 24, physical reads 2, read-ahead reads 22</pre></div></div>

<div id="attachment_846" class="wp-caption alignnone" style="width: 310px"><a href="http://sqlfool.com/wp-content/uploads/2009/04/queryplan3.jpg"><img src="http://sqlfool.com/wp-content/uploads/2009/04/queryplan3-300x273.jpg" alt="Filtered Query Plan" title="queryplan3" width="300" height="273" class="size-medium wp-image-846" /></a><p class="wp-caption-text">Filtered Query Plan</p></div>
<p>As expected, we get the best results with our filtered index scan.  </p>
<p>You'll notice that I did *not* create the index on the [SpecialOfferID] column like I did in [IX_Sales_SalesOrderDetail_SpecialOfferID].  This is because my query doesn't care what my [SpecialOfferID] value is, just as long as it's not equal to 1.  My non-filtered NC index was created on [SpecialOfferID] because it needed to navigate the B-TREE to find the records where [SpecialOfferID] <> 1.  With my filtered index, the query optimizer knows that all of my records already meet the criteria, so doesn't need to navigate through the index to find the matching results.  </p>
<p>We could choose to include the [SpecialOfferID] data in our filtered index, but we'd most likely want to make it an included column rather than part of the index key.  In fact, it's important to note that, if I don't add [SpecialOfferID] as an included column and I want to return it in the results, i.e.</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">SELECT</span> SalesOrderID
    , SpecialOfferID
    , <span style="color: #FF00FF;">COUNT</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">*</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'CountOfLineItem'</span>
    , <span style="color: #FF00FF;">SUM</span><span style="color: #808080;">&#40;</span>LineTotal<span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'SumOfLineTotal'</span>
<span style="color: #0000FF;">FROM</span> Sales.<span style="color: #202020;">SalesOrderDetail</span>
<span style="color: #0000FF;">WHERE</span> SpecialOfferID <span style="color: #808080;">&lt;&gt;</span> <span style="color: #000;">1</span>
<span style="color: #0000FF;">GROUP</span> <span style="color: #0000FF;">BY</span> SalesOrderID
    , SpecialOfferID;</pre></div></div>

<p><strong>my filtered index will not be used</strong> and I will instead scan on the clustered index once more (assuming [IX_Sales_SalesOrderDetail_SpecialOfferID] does not exist).  This is because the <strong>filtering criteria is not included anywhere on the actual index page</strong>.  This is actually good news, in my opinion, since it allows you to create even leaner indexes.  And like I already mentioned, if you do need the data returned, you can always add the filtering criteria as included columns.</p>
<p>What if you're trying to find out whether or not an index is filtered, and what it's filtered on?  The sys.indexes catalog view has been updated in 2008 to include this information:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">SELECT</span> name, has_filter, filter_definition
<span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">indexes</span> 
<span style="color: #0000FF;">WHERE</span> name In <span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'IX_Sales_SalesOrderDetail_SpecialOfferID'</span>
    , <span style="color: #FF0000;">'FIX_Sales_SalesOrderDetail_SpecialOfferID_Filtered'</span>
    , <span style="color: #FF0000;">'PK_SalesOrderDetail_SalesOrderID_SalesOrderDetailID'</span><span style="color: #808080;">&#41;</span>;</pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">name                                                   has_filter filter_definition
------------------------------------------------------ ---------- -------------------------
FIX_Sales_SalesOrderDetail_SpecialOfferID_Filtered     1          ([SpecialOfferID]&lt;&gt;(1))
IX_Sales_SalesOrderDetail_SpecialOfferID               0          NULL
PK_SalesOrderDetail_SalesOrderID_SalesOrderDetailID    0          NULL</pre></div></div>

<p>I personally recommend Kimberly Tripp's system stored proc, <a href="http://www.sqlskills.com/blogs/kimberly/post/sp_helpindex2-to-show-included-columns-(20052b)-and-filtered-indexes-(2008)-which-are-not-shown-by-sp_helpindex.aspx" target="_blank">sp_helpindex2</a>.  It returns a lot of good information about your indexes, such as included columns and filtering criteria.</p>
<p>That's all I have for today.  Hopefully, you now understand how powerful filtered indexes can be.  When used properly, filtered indexes can use less space, consume less IO, and improve overall query performance.  </p>
]]></content:encoded>
			<wfw:commentRss>http://sqlfool.com/2009/04/filtered-indexes-what-you-need-to-know/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>
