We have made last name the primary key in this table
Now lets import some rows into the table and check the fragmentation
Notice the fragmentation at 96.48% and all we did was one import of 16426 records. So now we have several questions:
- How bad is this? Fragmentation causes SQL Server to skip around to read data from your tables. For a one time read on a small table this is virtually meaningless. In a job that may need to read millions of records, this could tear apart your performance.
- Ok this is bad. How did it happen? The primary key on a table is clustered. This means the data will be stored according to the primary key. In our case, last name. When data doesn't come in the same way you store it (i.e. Customer names are not coming in alphabetically, but rather randomly) SQL Server must constantly split pages to store the data correctly. This causes data to be "fragmented" into multiple areas of the disk instead of one continuous stream.
- How can I fix it? Running regular maintenance on the table will fix the problem. Rebuild the indexes and reorganize the indexes (Fragmentation less than 30% reorganize. if it is >= 30% Rebuild).
How can I avoid this problem? Store the data in the way it comes in. Now for random last names coming in this is impossible right? Wrong! One way to ensure data is always store in the way it comes in is by creating an identity seed. This is a meaningless number that is simply incremented each time a row is added. Set your primary key to this identity seed and data is always coming in numerically and one higher than the last record. Creating an identity seed is simple enough. Just go into the properties of the column you are creating, set identity specification to yes, set (is identity) to yes and you are done. This column will automatically increment so you don't want to set a value to this column during your import.
So here I have re-created the table with CustomerNumber as the primary key. CustomerNumber is also an identity seed.
Importing the same rows yields this result on fragmentation:
1.79% fragmentation. Much better!
Comments
Post a Comment