It’s quite a well known fact that indexes can be good for your queries. They offer a shorter route to your data, and take some load off your server. They achieve this by creating a Balanced Tree (B-Tree) with pointers to your data. So in a table with customer names, if you search for “Mark”, instead of doing a full table scan to check all data for the name “Mark”, an index on the name column will have all occurrences of the name “Mark”, and can take a direct route to get your data.
But why does this make your server happy?
I’m going to be working with some fabricated data for the example. All tables/indexes/data I’m using are available here if you want to play along! Sorry for the download site, I don’t have proper web hosting yet.
In my example I’m using Regions, but it can be any data you like to test the principle.
I’ll cycle through the steps, and then go through the output.
- Clear your buffer using DBCC DROPCLEANBUFFERS – http://msdn.microsoft.com/en-us/library/ms187762.aspx
- Before your query, you want to Set Statistics IO on – http://msdn.microsoft.com/en-us/library/ms184361.aspx
- Your query in full should look like :
- Set Statistics IO on
- Select Region from dbo.IndexTest
- Turn on “Include Actual Execution Plan” in your query tool bar to verify the route the query is taking
- Run the query and examine
So with the inclusion of the index, I’ve reduced the amount of pages manipulated to 99, and I’m only using 792KB of memory/space. It’s exactly the same table, exactly the same amount of rows returned, but with the inclusion of an index, I’ve almost halved the amount of resources required to get my query back.
This example is obviously on a very small scale, and you’d be right not to be worried about saving yourself 600KB of memory on a production server. But scale it up by 100, or 1000, and suddenly the resources being saved are extremely significant.
This is just something I found interesting when I started digging a bit deeper, I always knew indexes were good for queries, but I never really thought to ask why!
So a slightly random blog post this time around, but it’s something I’ve meant to cover for a while. The more you know and all that!
Stephen