Filtered Indexes Work-Around
Filed under: Performance & Tuning, SQL 2008, SQL Tips, Syndication
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:
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.
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.
First, create a table to play with and populate it with some bogus data:
CREATE TABLE dbo.filteredIndexTest ( myID INT IDENTITY(1,3) , myDate SMALLDATETIME , myData CHAR(100) CONSTRAINT PK_filteredIndexTest PRIMARY KEY CLUSTERED(myID) ); SET NOCOUNT ON; DECLARE @DATE SMALLDATETIME = '2010-01-01'; WHILE @DATE < '2010-02-01' BEGIN INSERT INTO dbo.filteredIndexTest ( myDate , myData ) SELECT @DATE , 'Date: ' + CONVERT(VARCHAR(20), @DATE, 102); SET @DATE = DATEADD(MINUTE, 1, @DATE); END; SELECT COUNT(*) FROM dbo.filteredIndexTest;
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:
CREATE NONCLUSTERED INDEX IX_filteredIndexTest_1 ON dbo.filteredIndexTest(myDate) Include (myData) WHERE myDate >= '2010-01-27'; SELECT DISTINCT myData FROM dbo.filteredIndexTest WHERE myDate >= '2010-01-28';
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.
DECLARE @myDate1 SMALLDATETIME = '2010-01-28'; SELECT DISTINCT myData FROM dbo.filteredIndexTest WHERE myDate >= @myDate1;
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.
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.
DECLARE @mySQL1 NVARCHAR(2000) , @myParam NVARCHAR(2000) = '@p_myDate2 smalldatetime' , @myDate2 SMALLDATETIME = '2010-01-28'; SET @mySQL1 = 'Select Distinct myData From dbo.filteredIndexTest Where myDate >= @p_myDate2'; EXECUTE SP_EXECUTESQL @mySQL1, @myParam, @p_myDate2 = @myDate2;
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:
DECLARE @mySQL2 NVARCHAR(2000) , @myDate3 SMALLDATETIME = '2010-01-28'; SET @mySQL2 = 'Select Distinct myData From dbo.filteredIndexTest Where myDate >= ''' + CAST(@myDate3 AS VARCHAR(20)) + ''''; EXECUTE SP_EXECUTESQL @mySQL2; -- Drop Table dbo.filteredIndexTest;
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.
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.
There’s an even easier work-around for this problem that Dave (http://www.crappycoding.com) shared with me: recompile.
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:
DECLARE @myDate4 SMALLDATETIME = '2010-01-28'; SELECT DISTINCT myData FROM dbo.filteredIndexTest WHERE myDate >= @myDate4 OPTION (RECOMPILE); DECLARE @myDate5 SMALLDATETIME = '2010-01-20'; SELECT DISTINCT myData FROM dbo.filteredIndexTest WHERE myDate >= @myDate5 OPTION (RECOMPILE);
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.
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.
Update:
Alex Kuznetsov (http://www.simple-talk.com/author/alex-kuznetsov/) shared this method too:
DECLARE @myDate1 SMALLDATETIME = '2010-01-28'; SELECT DISTINCT myData FROM dbo.filteredIndexTest WHERE myDate = @myDate1 AND myDate >= '2010-01-27';
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!
#PASSAwesomeness
Filed under: Miscellaneous, PASS, Performance & Tuning, Presentations, Syndication
Allen Kinsel on Twitter (@sqlinsaneo) recently started a new Twitter tag, #PASSAwesomeness, about all of the cool things about PASS Summit. I really like the tag, so I’m going to blatantly steal borrow it for this post.
First, and long overdue, I want to give a brief recap of the East Iowa SQL Saturday. On October 17th, our local PASS chapter, 380PASS, sponsored our first ever SQL Saturday at the University of Iowa in Iowa City. By all accounts, the event was a great success! We had 90 attendees, 11 speakers, and 21 sessions. We received numerous compliments on the quality of the speakers, the niceness of the facilities, and the abundance of food. Not too shabby for our first time hosting the event, if I do say so myself.
I’d like to thank all of our wonderful speakers, especially those who traveled from out of town and out of state, for making this event such a success. I’d also like to thank our amazing volunteers for helping put this all together. Lastly, but certainly not least, I’d like to thank our generous sponsors, without whom this event would not be possible. Because this event went so smoothly and was so well received in the community, we’ve already started planning our next big SQL event! In the meantime, don’t forget to check out our monthly 380PASS meetings to tide you over.
I’d also like to take a moment to discuss the PASS Summit. Unless you’re a DBA who’s been living under a rock, you’ve probably heard of the PASS Summit. If you *have* been living under a rock — and hey, I’m not poking fun, I used to live under a rock, too! — then what you need to know is that the Summit is the largest SQL Server conference in the world. It’s a gathering of Microsoft developers and SQL Server gurus; the rest of us show up to try to absorb as much from them as possible. Since I’ve recently moved to the Business Intelligence team, I’m extremely excited to delve into the amazing amount of BI content offered.
I’m also deeply honored to be presenting at the Summit this year on some of the performance tuning techniques I’ve used with great success in my production environments. The session is titled, Super Bowl, Super Load – A Look At Performance Tuning for VLDB’s. If you’re interested in performance tuning or VLDB (very large database) topics, consider stopping by to catch my session. From what I can tell, I’ll be presenting on Tuesday from 10:15am – 11:30am in room(s?) 602-604.
If you read my blog, or if we’ve ever interacted in any way on the internet — Twitter, LinkedIn, e-mails, blog comments, etc. — please stop by and say “hi”! Aside from all of the awesome SQL Server content, I’m really looking forward to meeting as many new folks as possible.
And on that note…
Getting to meet all of the amazing SQL Server professionals out there who have inspired and encouraged me in so many ways #PASSAwesomeness
Partitioning Tricks
Filed under: Miscellaneous, Performance & Tuning, SQL 2008, SQL Tips, Syndication
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 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 SQL Server Partition Management 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…
Add Check Constraints After Loading Data
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:
.Net SqlClient Data Provider: Msg 4972, Level 16, State 1, Line 1
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’.
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.
Replicating Into Partitioned and Non-Partitioned Tables
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:
/* Identify which servers get the partitioned version */ IF @@SERVERNAME In ('yourServerNameList') BEGIN /* Create your partitioning scheme if necessary */ IF Not Exists(SELECT * FROM sys.partition_schemes WHERE name = 'InsertPartitionScheme') CREATE PARTITION SCHEME InsertPartitionScheme AS PARTITION InsertPartitionFunction ALL TO ([PRIMARY]); /* Create your partitioning function if necessary */ IF Not Exists(SELECT * FROM sys.partition_functions WHERE name = 'InsertPartitionFunction') CREATE PARTITION FUNCTION InsertPartitionFunction (SMALLDATETIME) AS RANGE RIGHT FOR VALUES ('insertValues'); /* Create a partitioned version of your table */ CREATE TABLE [dbo].[yourTableName] ( [yourTableSchema] ) ON InsertPartitionScheme([partitioningKey]); END ELSE BEGIN /* Create a non-partitioned version of your table */ CREATE TABLE [dbo].[yourTableName] ( [yourTableSchema] ) ON [PRIMARY]; END
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.
Compress Old Partitions
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:
/* Apply compression to your partitioned table */ ALTER TABLE dbo.yourTableName Rebuild Partition = All WITH ( Data_Compression = Page ON Partitions(1 TO 9) , Data_Compression = ROW ON Partitions(10 TO 11) , Data_Compression = NONE ON Partitions(12) ); /* Apply compression to your partitioned index */ ALTER INDEX YourPartitionedIndex ON dbo.yourTableName Rebuild Partition = All WITH ( Data_Compression = Page ON Partitions(1 TO 9) , Data_Compression = ROW ON Partitions(10 TO 11) , Data_Compression = NONE ON Partitions(12) ); /* Apply compression to your unpartitioned index */ ALTER INDEX YourUnpartitionedIndex ON dbo.yourTableName Rebuild WITH (Data_Compression = ROW);
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.
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.
Looking for more information on table partitioning? Check out my overview of partitioning, my example code, and my article on indexing on partitioned tables.
Monitoring Process for Performance Counters
Filed under: Performance & Tuning, Syndication, T-SQL Scripts
Recently I needed to create a process to monitor performance counters over a short period of time. We were going to implement a change and we wanted to compare performance before and after to see if there was any impact.
To do this, I first created a couple of tables. One table is used to actually store the monitored values. The second table is used for configuration; you insert only the counters you want to monitor.
/* Create the table to store our logged perfmon counters */ CREATE TABLE dbo.dba_perfCounterMonitor ( capture_id INT IDENTITY(1,1) Not Null , captureDate SMALLDATETIME Not Null , objectName NVARCHAR(128) Not Null , counterName NVARCHAR(128) Not Null , instanceName NVARCHAR(128) Not Null , VALUE FLOAT(6) Not Null , valueType NVARCHAR(10) Not Null CONSTRAINT PK_dba_perfCounterMonitor PRIMARY KEY CLUSTERED(capture_id) ); /* Create the table that controls which counters we're going to monitor */ CREATE TABLE dbo.dba_perfCounterMonitorConfig ( objectName NVARCHAR(128) Not Null , counterName NVARCHAR(128) Not Null , instanceName NVARCHAR(128) Null );
If you leave the instanceName NULL in the config table, it’ll monitor all instances. Now we’re going to insert some sample performance counters into the config table. The counters you’re interested in can, and likely will, vary.
/* Insert some perfmon counters to be monitored */ INSERT INTO dbo.dba_perfCounterMonitorConfig SELECT 'SQLServer:Buffer Manager', 'Page Life Expectancy', Null UNION All SELECT 'SQLServer:Locks', 'Lock Requests/sec', Null UNION All SELECT 'SQLServer:Locks', 'Lock Waits/sec', Null UNION All SELECT 'SQLServer:Locks', 'Lock Wait Time (ms)', Null UNION All SELECT 'SQLServer:Buffer Manager', 'Page reads/sec', Null UNION All SELECT 'SQLServer:Buffer Manager', 'Page writes/sec', Null UNION All SELECT 'SQLServer:Buffer Manager', 'Buffer cache hit ratio', Null UNION All SELECT 'SQLServer:Databases', 'Transactions/sec', 'AdventureWorks' UNION All SELECT 'SQLServer:General Statistics', 'Processes blocked', Null;
Now let’s create our proc. This proc will run for a specified time period and will *average* the counters over that time. I personally take snapshots every 15 seconds for 4 minutes; I have a scheduled task that runs this every 5 minutes. It’s not perfect, but it gives me a good idea of what’s happening on the server.
CREATE PROCEDURE dbo.dba_perfCounterMonitor_sp /* Declare Parameters */ @samplePeriod INT = 240 /* how long to sample, in seconds */ , @sampleRate CHAR(8) = '00:00:15' /* how frequently to sample, in seconds */ , @displayResults BIT = 0 /* display the results when done */ AS /********************************************************************************* Name: dba_perfCounterMonitor_sp Author: Michelle Ufford, http://sqlfool.com Purpose: Monitors performance counters. Uses the dba_perfCounterMonitorConfig table to manage which perf counters to monitor. @samplePeriod - specifies how long the process will try to monitor performance counters; in seconds. @sampleRate - how long inbetween samples; in seconds. The average values over sample period is then logged to the dba_perfCounterMonitor table. Notes: There are 3 basic types of performance counter calculations: Value/Base: these calculations require 2 counters. The value counter (cntr_type = 537003264) has to be divided by the base counter (cntr_type = 1073939712). Per Second: these counters are store cumulative values; the value must be compared at 2 different times to calculate the difference (cntr_type = 537003264). Point In Time: these counters show what the value of the counter is at the current point-in-time (cntr_type = 65792). No calculation is necessary to derive the value. Called by: DBA Date User Description ---------------------------------------------------------------------------- 2009-09-04 MFU Initial Release ********************************************************************************* Exec dbo.dba_perfCounterMonitor_sp @samplePeriod = 60 , @sampleRate = '00:00:01' , @displayResults = 1; *********************************************************************************/ SET NOCOUNT ON; SET XACT_Abort ON; SET Ansi_Padding ON; SET Ansi_Warnings ON; SET ArithAbort ON; SET Concat_Null_Yields_Null ON; SET Numeric_RoundAbort OFF; BEGIN /* Declare Variables */ DECLARE @startTime DATETIME , @endTime DATETIME , @iteration INT; SELECT @startTime = GETDATE() , @iteration = 1; DECLARE @samples TABLE ( iteration INT Not Null , objectName NVARCHAR(128) Not Null , counterName NVARCHAR(128) Not Null , instanceName NVARCHAR(128) Not Null , cntr_value FLOAT Not Null , base_value FLOAT Null , cntr_type BIGINT Not Null ); BEGIN Try /* Start a new transaction */ BEGIN TRANSACTION; /* Grab all of our counters */ INSERT INTO @samples SELECT @iteration , RTRIM(dopc.OBJECT_NAME) , RTRIM(dopc.counter_name) , RTRIM(dopc.instance_name) , RTRIM(dopc.cntr_value) , (SELECT cntr_value FROM sys.dm_os_performance_counters AS dopc1 WHERE dopc1.OBJECT_NAME = pcml.objectName And dopc1.counter_name = pcml.counterName + ' base' And dopc1.instance_name = IsNull(pcml.instanceName, dopc.instance_name)) , dopc.cntr_type FROM sys.dm_os_performance_counters AS dopc Join dbo.dba_perfCounterMonitorConfig AS pcml ON dopc.OBJECT_NAME = pcml.objectName And dopc.counter_name = pcml.counterName And dopc.instance_name = IsNull(pcml.instanceName, dopc.instance_name); /* During our sample period, grab our counter values and store the results */ WHILE GETDATE() < DATEADD(SECOND, @samplePeriod, @startTime) BEGIN SET @iteration = @iteration + 1; INSERT INTO @samples SELECT @iteration , RTRIM(dopc.OBJECT_NAME) , RTRIM(dopc.counter_name) , RTRIM(dopc.instance_name) , dopc.cntr_value , (SELECT cntr_value FROM sys.dm_os_performance_counters AS dopc1 WHERE dopc1.OBJECT_NAME = pcml.objectName And dopc1.counter_name = pcml.counterName + ' base' And dopc1.instance_name = IsNull(pcml.instanceName, dopc.instance_name)) , dopc.cntr_type FROM sys.dm_os_performance_counters AS dopc Join dbo.dba_perfCounterMonitorConfig AS pcml ON dopc.OBJECT_NAME = pcml.objectName And dopc.counter_name = pcml.counterName And dopc.instance_name = IsNull(pcml.instanceName, dopc.instance_name); /* Wait for a small delay */ WAITFOR Delay @sampleRate; END; /* Grab our end time for calculations */ SET @endTime = GETDATE(); /* Store the average of our point-in-time counters */ INSERT INTO dbo.dba_perfCounterMonitor ( captureDate , objectName , counterName , instanceName , VALUE , valueType ) SELECT @startTime , objectName , counterName , instanceName , AVG(cntr_value) , 'value' FROM @samples WHERE cntr_type = 65792 GROUP BY objectName , counterName , instanceName; /* Store the average of the value vs the base for cntr_type = 537003264 */ INSERT INTO dbo.dba_perfCounterMonitor ( captureDate , objectName , counterName , instanceName , VALUE , valueType ) SELECT @startTime , objectName , counterName , instanceName , AVG(cntr_value)/AVG(IsNull(base_value, 1)) , 'percent' FROM @samples WHERE cntr_type = 537003264 GROUP BY objectName , counterName , instanceName; /* Compare the first and last values for our cumulative, per-second counters */ INSERT INTO dbo.dba_perfCounterMonitor ( captureDate , objectName , counterName , instanceName , VALUE , valueType ) SELECT @startTime , objectName , counterName , instanceName , (MAX(cntr_value) - MIN(cntr_value)) / DATEDIFF(SECOND, @startTime, @endTime) , 'value' FROM @samples WHERE cntr_type = 272696576 GROUP BY objectName , counterName , instanceName; /* Should we display the results of our most recent execution? */ IF @displayResults = 1 SELECT captureDate , objectName , counterName , instanceName , VALUE , valueType FROM dbo.dba_perfCounterMonitor WITH (NoLock) WHERE captureDate = CAST(@startTime AS SMALLDATETIME) ORDER BY objectName , counterName , instanceName; /* If you have an open transaction, commit it */ IF @@TRANCOUNT > 0 COMMIT TRANSACTION; END Try BEGIN Catch /* Whoops, there was an error... rollback! */ IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION; /* Return an error message and log it */ EXECUTE dbo.dba_logError_sp; END Catch; SET NOCOUNT OFF; RETURN 0; END Go
Like I said, it’s not perfect, but it gets the job done.
Getting an error about dba_logError_sp? Take a look at my error handling proc.
Overhead in Non-Unique Clustered Indexes
Filed under: Internals, Performance & Tuning, SQL 2008, Syndication
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 necessarily consume more space and overhead; 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.
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.
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.
USE sandbox; Go /* Unique, clustered index, no duplicate values */ CREATE TABLE dbo.uniqueClustered ( myDate DATE Not Null , myNumber INT Not Null , myColumn CHAR(995) Not Null ); CREATE UNIQUE CLUSTERED INDEX CIX_uniqueClustered ON dbo.uniqueClustered(myDate); /* Non-unique clustered index, but no duplicate values */ CREATE TABLE dbo.nonUniqueNoDups ( myDate DATE Not Null , myNumber INT Not Null , myColumn CHAR(995) Not Null ); CREATE CLUSTERED INDEX CIX_nonUniqueNoDups ON dbo.nonUniqueNoDups(myDate); /* Non-unique clustered index, duplicate values */ CREATE TABLE dbo.nonUniqueDuplicates ( myDate DATE Not Null , myNumber INT Not Null , myColumn CHAR(995) Not Null ); CREATE CLUSTERED INDEX CIX_nonUniqueDuplicates ON dbo.nonUniqueDuplicates(myDate);
I’m going to use the date 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.
/* Populate some test data */ SET NOCOUNT ON; DECLARE @myDate DATE = '1990-01-01' , @myNumber INT = 1; WHILE @myDate < '2010-01-01' BEGIN INSERT INTO dbo.uniqueClustered SELECT @myDate, @myNumber, 'data'; INSERT INTO dbo.nonUniqueNoDups SELECT @myDate, @myNumber, 'data'; INSERT INTO dbo.nonUniqueDuplicates SELECT '2009-01-01', @myNumber, 'data'; SELECT @myDate = DATEADD(DAY, 1, @myDate) , @myNumber += 1; END;
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:
/* Look at the details of our indexes */ /* Unique, clustered index, no duplicate values */ SELECT 'unique' AS 'type', page_count, avg_page_space_used_in_percent, record_count , min_record_size_in_bytes, max_record_size_in_bytes FROM sys.dm_db_index_physical_stats(DB_ID(), OBJECT_ID(N'uniqueClustered'), Null, Null, N'Detailed') WHERE index_level = 0 UNION All /* Non-unique clustered index, but no duplicate values */ SELECT 'non-unique, no dups', page_count, avg_page_space_used_in_percent, record_count , min_record_size_in_bytes, max_record_size_in_bytes FROM sys.dm_db_index_physical_stats(DB_ID(), OBJECT_ID(N'nonUniqueNoDups'), Null, Null, N'Detailed') WHERE index_level = 0 UNION All /* Non-unique clustered index, duplicate values */ SELECT 'duplicates', page_count, avg_page_space_used_in_percent, record_count , min_record_size_in_bytes, max_record_size_in_bytes FROM sys.dm_db_index_physical_stats(DB_ID(), OBJECT_ID(N'nonUniqueDuplicates'), Null, Null, N'Detailed') WHERE index_level = 0;
Here’s the results:
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
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.
Now let’s take a look at the actual data pages. For this, I’m going to use my page internals proc.
Execute dbo.dba_viewPageData_sp @databaseName = 'sandbox' , @tableName = 'sandbox.dbo.uniqueClustered' , @indexName = 'CIX_uniqueClustered';
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:
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†††††††††††††††††††††††††††††††††††. Slot 0 Column 1 Offset 0x4 Length 3 Length (physical) 3 myDate = 1990-01-01 Slot 0 Column 2 Offset 0x7 Length 4 Length (physical) 4 myNumber = 1 Slot 0 Column 3 Offset 0xb Length 995 Length (physical) 995 myColumn = data
Now let’s look at the table that has a non-unique clustered index but no duplicates:
EXECUTE dbo.dba_viewPageData_sp @databaseName = 'sandbox' , @tableName = 'sandbox.dbo.nonUniqueNoDups' , @indexName = 'CIX_nonUniqueNoDups';
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):
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†††††††††††††††††††††††††††††††††††. Slot 0 Column 0 Offset 0x0 Length 4 Length (physical) 0 UNIQUIFIER = 0 Slot 0 Column 1 Offset 0x4 Length 3 Length (physical) 3 myDate = 1990-01-01 Slot 0 Column 2 Offset 0x7 Length 4 Length (physical) 4 myNumber = 1 Slot 0 Column 3 Offset 0xb Length 995 Length (physical) 995 myColumn = data Slot 1 Offset 0x451 Length 1009 Record Type = PRIMARY_RECORD Record Attributes = NULL_BITMAP Record Size = 1009 Memory Dump @0x62FDC451 00000000: 1000ee03 c4150b02 00000064 61746120 †..î.Ä......data [...] 000003F0: 00†††††††††††††††††††††††††††††††††††. Slot 1 Column 0 Offset 0x0 Length 4 Length (physical) 0 UNIQUIFIER = 0 Slot 1 Column 1 Offset 0x4 Length 3 Length (physical) 3 myDate = 1990-01-02 Slot 1 Column 2 Offset 0x7 Length 4 Length (physical) 4 myNumber = 2 Slot 1 Column 3 Offset 0xb Length 995 Length (physical) 995 myColumn = data
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.
Update: The DBCC God himself, Paul Randal, 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.
Now let’s look at our final case, a non-unique clustered index with duplicate key values:
EXECUTE dbo.dba_viewPageData_sp @databaseName = 'sandbox' , @tableName = 'sandbox.dbo.nonUniqueDuplicates' , @indexName = 'CIX_nonUniqueDuplicates';
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:
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†††††††††††††††††††††††††††††††††††. Slot 0 Column 0 Offset 0x0 Length 4 Length (physical) 0 UNIQUIFIER = 0 Slot 0 Column 1 Offset 0x4 Length 3 Length (physical) 3 myDate = 2009-01-01 Slot 0 Column 2 Offset 0x7 Length 4 Length (physical) 4 myNumber = 1 Slot 0 Column 3 Offset 0xb Length 995 Length (physical) 995 myColumn = data Slot 1 Offset 0x451 Length 1017 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†††††††††††††††††...ù..... Slot 1 Column 0 Offset 0x3f5 Length 4 Length (physical) 4 UNIQUIFIER = 1 Slot 1 Column 1 Offset 0x4 Length 3 Length (physical) 3 myDate = 2009-01-01 Slot 1 Column 2 Offset 0x7 Length 4 Length (physical) 4 myNumber = 2 Slot 1 Column 3 Offset 0xb Length 995 Length (physical) 995 myColumn = data
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.
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!
Performance Considerations of Data Types
Filed under: PASS, Performance & Tuning, SQL Tips, Syndication
I’ve just finished my first real content for the PASS Performance SIG. I decided to write on “Performance Considerations of Data Types,” as I think this is one of the easiest and most overlooked topics in performance tuning. Here’s a summary:
Selecting inappropriate data types, especially on large tables with millions or billions of rows, can have significant performance implications. In this article, I’ll explain why and offer suggestions on how to select the most appropriate data type for your needs. The primary focus will be on common data types in SQL Server 2005 and 2008, but I’ll also discuss some aspects of clustered indexes and column properties. Most importantly, I’ll show some examples of common data-type misuse.
If you’re interested in this content, you can find it here: Performance Considerations of Data Types.
Special thanks to Paul Randal and Paul Nielsen for providing me with technical reviews and great feedback. You guys are awesome!
Thanks also to Mladen Prajdic and Jeremiah Peschka for their great input. You guys are awesome, too!
A Look at Missing Indexes
Filed under: Performance & Tuning, Syndication, T-SQL Scripts
Tim Ford (@SQLAgentMan) recently blogged about his Top 5 SQL Server Indexing Best Practices. I thought it was a good list, and it inspired this blog post. I’ve recently been doing a little index spring cleaning, and I thought some people may be interested in the process I go through. So, here it is… a journey through madness an overview of my general missing index process.
I start with my trusty dba_missingIndexStoredProc table. If this table sounds completely foreign to you, check out my post, Find Missing Indexes In Stored Procs. Basically, I have a process that runs every night, scanning the XML of every query plan on the server to find procs that are possibly missing indexes. I then log the details for later action.
So I take a look at my table, and I find 8 stored procedures that are possibly missing indexes. Clicking on the XML link will show me the logged query plan:
Right clicking on the “Missing Index” description will give me the details of the recommended index:
Here’s an example of what SQL Server will return for you:
/* Missing Index Details from ExecutionPlan2.sqlplan The Query Processor estimates that implementing the following index could improve the query cost by 85.7327%. */ /* USE [msdb] GO CREATE NONCLUSTERED INDEX [<Name of Missing Index, sysname,>] ON [dbo].[sysjobhistory] ([job_id]) INCLUDE ([instance_id],[step_id],[sql_message_id],[sql_severity], [run_status],[run_date],[run_time],[run_duration],[operator_id_emailed], [operator_id_netsent],[operator_id_paged],[retries_attempted],[server]) GO */
I now compare the details of this proposed index to the missing index DMV suggestions, using this query:
SELECT t.name AS 'affected_table' , 'Create NonClustered Index IX_' + t.name + '_missing_' + CAST(ddmid.index_handle AS VARCHAR(10)) + ' On ' + ddmid.STATEMENT + ' (' + IsNull(ddmid.equality_columns,'') + CASE WHEN ddmid.equality_columns IS Not Null And ddmid.inequality_columns IS Not Null THEN ',' ELSE '' END + IsNull(ddmid.inequality_columns, '') + ')' + IsNull(' Include (' + ddmid.included_columns + ');', ';' ) AS sql_statement , ddmigs.user_seeks , ddmigs.user_scans , CAST((ddmigs.user_seeks + ddmigs.user_scans) * ddmigs.avg_user_impact AS INT) AS 'est_impact' , ddmigs.last_user_seek FROM sys.dm_db_missing_index_groups AS ddmig INNER JOIN sys.dm_db_missing_index_group_stats AS ddmigs ON ddmigs.group_handle = ddmig.index_group_handle INNER JOIN sys.dm_db_missing_index_details AS ddmid ON ddmig.index_handle = ddmid.index_handle INNER JOIN sys.tables AS t ON ddmid.OBJECT_ID = t.OBJECT_ID WHERE ddmid.database_id = DB_ID() --AND t.name = 'myTableName' ORDER BY CAST((ddmigs.user_seeks + ddmigs.user_scans) * ddmigs.avg_user_impact AS INT) DESC;
I usually find the data in both places, but not always. One reason why is because the missing index DMV will only store data since your last reboot. So if I’m taking a look at this DMV on Monday and I just rebooted on Sunday, I may not have enough history to give me meaningful recommendations. This is just something to be aware of.
What I’m looking for in this DMV is the number of user_seeks and the est_impact. Also, if I haven’t rebooted my server in a while, I take a look at last_user_seek so I can determine whether or not it’s still accurate.
Next, I take a look at my existing indexes using Kimberly Tripp’s sp_helpindex2 system stored proc. I use her proc instead of sp_helpindex because I need to see included columns.
If you’re wondering why I’m looking at existing indexes, the reason is because I’m looking for indexes that can be modified slightly to accommodate my missing index needs. By “modified slightly,” I mean that I’d only want to make a change to an existing index if it did not drastically change the size or composition of an index, i.e. adding one or two narrow columns as included columns. I do NOT mean making changes that double the size of your index; in those cases, you’d probably be better off creating a brand new index.
Looking at existing indexes is actually a pretty critical part of the puzzle. If I have a proc that only gets called a few times an hour and could benefit from a better index, I may not create that index if it means adding a wide, expensive index to a busy table. If I can make a small modification to an existing index, then there’s a greater chance I’ll make the change and cover my query.
At this point, I should have enough information to start making decisions. I was going to write out the path I normally take when making decisions, but I thought, “Hey! What a great time for a diagram.” So here you go:
Disclaimer: I’m *not* a Visio wizard, so if I butchered the use of certain symbols in my diagram, please let me know so I can a) fix it, and b) learn from it!
It’s hard to really put all of the decision paths into a single, small diagram like this. There’s a lot of variables that I’m not even touching here. But I think this is a fairly good “generic” representation of the path I take. When I hit an “end” process, it means I don’t create the missing index at this time. Maybe in the future, it’ll become necessary, but I prefer to err on the side of less indexes.
So there you have it, a brief look at my missing index process. Hopefully someone finds it helpful.
T-SQL Bitwise Operations
Filed under: Miscellaneous, Performance & Tuning, SQL Tips, Syndication
I’ve seen bit-product columns from time-to-time, mostly in SQL Server 2000 system tables, but it’s never been something I’ve had to work with. And when I’ve needed to, I’ve known how to figure out which options are selected, i.e. a bit product of 9 means options 8 and 1 are selected. If you’ve ever taken a look at the [status] column on the sysdatabases table (SQL 2000), you’ll know what I’m talking about.
What I’ve never known how to do, until recently, was calculate these options programmatically. That’s why, when I noticed the [freq_interval] on the sysschedules table was a bit-product column, I decided to spend a little time figuring it out. Fortunately for me, a couple of my awesome co-workers, Jeff M. and Jason H., have worked with this before and were able to explain it to me. And, it turns out, it’s actually quite easy.
Let me back up a few steps in case you’re not familiar with this topic. If you check out the Books Online entry for the sysschedules table (2005), you’ll notice the following statement:
freq_interval is one or more of the following:
1 = Sunday
2 = Monday
4 = Tuesday
8 = Wednesday
16 = Thursday
32 = Friday
64 = Saturday
When I looked at the actual value in the table, the schedule has a [freq_interval] value of 42, which is the sum of the bit values for the days selected.
If there were more than 7 options, the bit values would continue to double, i.e. 128, 256, etc. And regardless of how many bit values you select, you’re guaranteed one and only one possible answer, as the sum of all previous bit values will never exceed the next bit value:
1 + 2 = 3
1 + 2 + 4 = 7
1 + 2 + 4 + 8 = 15
Knowing this, I’m able to retrieve the values manually: I start with the highest bit value that does not exceed 42, then subtract it; I repeat until I’m left with 0.
So…
42 – 32 = 10
10 – 8 = 2
2 – 2 = 0
That means my job is scheduled to run on Friday’s (32), Wednesday’s (8), and Monday’s (2).
Now how do I do this with T-SQL? SQL Server provides an operator specifically for this task: the bitwise AND operator (&). For now, I’m going to skip the “why” behind this and just get to the practical application. If you’re interested in the “why,” let me know and I’ll write a follow-up post on binary and logical AND and OR operations.
For example, to use the bitwise AND to find out which days are selected…
SELECT 42 & 1 AS 'Sunday' , 42 & 2 AS 'Monday' , 42 & 4 AS 'Tuesday' , 42 & 8 AS 'Wednesday' , 42 & 16 AS 'Thursday' , 42 & 32 AS 'Friday' , 42 & 64 AS 'Saturday';
… will return …
Sunday Monday Tuesday Wednesday Thursday Friday Saturday ----------- ----------- ----------- ----------- ----------- ----------- ----------- 0 2 0 8 0 32 0
If the result is not equal to zero, then that day is selected. Easy as key lime pie, right?
Now let’s take it a step further and create our own working example. Let’s say we’re going to track the characteristics of various objects in a single bit-product column (note: this is not necessarily the best way to accomplish this in the real world, but it’s a good illustration). First, set up a table to use in our example. This table will have a column, [attributes], which will hold the sum of our bit values.
CREATE TABLE myTable ( id INT IDENTITY(1,1) , item VARCHAR(10) , attributes INT ); INSERT INTO myTable SELECT 'Broccoli', 200 UNION All SELECT 'Tomato', 193 UNION All SELECT 'Car', 276 UNION All SELECT 'Ball', 292;
Next, we’re going to create a table variable that holds characteristics and their values. We’ll then join these two tables together to see which attributes exist for each item.
DECLARE @statusLookup TABLE ( attribute INT , VALUE VARCHAR(10) ); INSERT INTO @statusLookup SELECT 1, 'Red' UNION All SELECT 4, 'Blue' UNION All SELECT 8, 'Green' UNION All SELECT 16, 'Metal' UNION All SELECT 32, 'Plastic' UNION All SELECT 64, 'Plant' UNION All SELECT 128, 'Edible' UNION All SELECT 256, 'Non-Edible'; SELECT a.item, b.VALUE FROM myTable a Cross Join @statusLookup b WHERE a.attributes & b.attribute <> 0 ORDER BY a.item , b.VALUE
You should get this result:
item value ---------- ---------- Ball Blue Ball Non-Edible Ball Plastic Broccoli Edible Broccoli Green Broccoli Plant Car Blue Car Metal Car Non-Edible Tomato Edible Tomato Plant Tomato Red
Great, now we know broccoli is edible! Let’s apply a little XML to clean up the results…
SELECT a.item , REPLACE( REPLACE( REPLACE(( SELECT VALUE FROM @statusLookup AS b WHERE a.attributes & b.attribute <> 0 ORDER BY b.VALUE FOR XML Raw) , '"/><row value="', ', '), '<row value="', ''), '"/>', '') AS 'attributes' FROM myTable a ORDER BY a.item;
item attributes ---------------------------------------- Ball Blue, Non-Edible, Plastic Broccoli Edible, Green, Plant Car Blue, Metal, Non-Edible Tomato Edible, Plant, Red
Voila! There you have it, how to use the bitwise AND (&) operator to retrieve multiple values from a bit-product column. Pretty neat stuff!
Special thanks to Jeff M. and Jason H. for their assistance.
Happy Coding!
Michelle Ufford (aka SQLFool)
Source: http://sqlfool.com/2009/02/bitwise-operations/
Ramblings on Super Bowl and PASS
Super Bowl 2009
As many of you know, I’m a DBA at GoDaddy.com, which had 2 commercials in this year’s Super Bowl. If you saw the commercials during the game or went to our website for the “internet only” versions, let me know; I have no control over the content of the ads, but I’m still interested in your opinions. But comments on ad content aside, the commercials continue to prove very effective for driving traffic to our website and, in turn, generating income. (Don’t believe me? Read this and this article on finance.yahoo.com).
We typically get some pretty large spikes the minutes immediately following a commercial airing, and this year was no exception! We spent quite a bit of time throughout the year tuning our systems to support Super Bowl traffic, especially in the few weeks preceding the big game. By all accounts, this year’s efforts have paid off; our database servers exceeded expectations. I don’t think I’m allowed to go into specifics, but I can mention some server stats. During the spikes, my primary server reached 27k transactions per second, no timeouts, and very good response times. In fact, I estimate we decreased our recovery time by around 80% compared to last year.
Why do I mention all of this? Well, there’s the bragging aspect, of course
. But more importantly, I bring it up to give credence to some of the performance tuning articles I’ve written in the past, like:
- Regularly defrag your indexes
- Evaluate the effectiveness of your indexes
- Partition your large tables
- Use TVP or XML for bulk inserts
- Use non-aligned indexes for single record look-ups (partitioning)
Keep in mind, there’s rarely a “magic bullet” for performance tuning, and what worked for me may not work for you. If you have any questions, please feel free to leave me a comment or send me an e-mail, and I’ll do my best to respond.
If you’re interested in more information on effective performance tuning, make sure to check out the Performance Tuning Section on SQLServerPedia.com.
I380 PASS
I’ve been pleasantly surprised with the number of inquiries I’ve received regarding the I380 PASS Chapter (serving the East Iowa area of Cedar Rapids and Iowa City), so I’ll continue to post updates to my blog.
As I’ve mentioned before, we’re now officially a PASS Chapter, and we’re currently in the planning stages of our first meeting. We have one confirmed key sponsor, Quest Software (woot!), and we’re speaking with a couple of other possible sponsors. Side note: if you’re interested in sponsoring our group, I’d love to hear from you! E-mail me at michelle @ sqlfool dot com.
We’re currently planning to have meetings on the second Tuesday of every month, with our first meeting on Tuesday, March 10th 2009. We have a confirmed speaker but not a confirmed topic, and we’re actively working on a meeting location. Please keep in mind that all of these details are subject to change.
If you’re in the area and would like to attend, or know someone who should attend, please drop me a line!
Creating a 60 GB Index
Recently, I needed to create an index on a 1.5 billion row table. I’ve created some large indexes before, but this was the largest, so I thought I’d share my experience in case anyone was interested.
The plan was to create the following index:
CREATE NONCLUSTERED INDEX IX_indexName_unpartitioned ON databaseName.dbo.tableName(columnList) Include (includedColumnList) WITH (MaxDop = 1, Online = ON, Sort_In_TempDB = ON) ON [PRIMARY];
This is an unpartitioned, non-clustered index being built on a partitioned table. Normally, when you build an aligned partitioned index, the index creation process requires less memory and has less noticeable impact on the system, because each partition is handled individually, one at a time. But as this is an unpartitioned (unaligned) index, each partition was built concurrently, requiring more memory and causing a greater impact on performance. Because of this, I needed to restrict the process to MaxDop 1; otherwise, the server would suffer because of too much memory pressure.
I chose Sort_In_TempDB = On because:
- I’m building this index online on a very busy table and cannot afford to impact normal oeprations. By using Sort_In_TempDB = On, index transactions are separated from user transactions, allowing the user transaction log to be truncated. *
- TempDB is on a different volume and therefore should reduce the duration of the operation.
- The recovery for the user database is full, and the recovery for the TempDB is simple. Sorting in TempDB would minimize logging.
* Note: the transaction log for the user database still grew at a much faster rate than normal and had to be closely monitored during this operation to ensure enough free space remained.
The size of the indexed columns is 25 bytes. So I ran my calculations and came up with 36gb space requirement. We increased TempDB to 50gb and gave it a go. An hour later… ERROR. The process terminated because there would not be enough space free in TempDB to complete the operation. Obviously, my calculations were incorrect. After speaking with Chris Leonard, a man who is way too smart for his own good, I realized I had not included my clustered index in the size calculations. Doh.
Re-running my estimates, here’s what I came up with:
| Index Size | 25 | bytes |
| Clustered Index Size | 16 | bytes |
| Records per Page | 197 | |
| Est. Rows | 1,575,000,000 | |
| Est. Number of Pages | 7,995,000 | |
| Space Requirements | 59 | GB |
Obviously, 50gb of free space just wasn’t going to cut it. I decided to give TempDB a little wiggle room and bumped up the space in TempDB to 70gb (not as easy as you’d imagine, I had to requisition more space on the SAN), then re-ran the operation. Success! The process completed in 3 hours and 24 minutes. There was a mild increase in CPU, but no applications or users experienced any issues.
For those interested in the particulars: this was used for a single-record look-up and could not be filtered by the partitioning key. The non-partitioned version of this index has 80% less reads and 11% less CPU than its partitioned counterpart.
If you’re interested in learning more about indexes, here’s some recommended reading:








