Thursday, July 25, 2013

Indexes in sql server

When performance matters indexes comes first in terms of query performance. Poorly designed indexes and a lack of indexes are primary sources of database application bottlenecks. Designing efficient indexes is paramount to achieving good database and application performance.

 Large numbers of indexes on a table affect the performance of INSERT, UPDATE, DELETE, and MERGE statements because changes on table also make changes on indexes. If we have more select statements like we have in Data Warehouse than heavily indexes are preferable.

Indexes are one kind of pattern of storing data for faster retrieval. When you create an index on table it basically creates B-Tree (Balanced Tree) structure. It follows format for easier search of data. 

When you do not have any index on table than data get stored in random fashion which is also called table on Heap. Data retrieval are much slower when you compare table on a heap and table on an index.



In B-tree structure top level and intermediate level have nodes which stored key values based on what you are creating indexes. On the bottom level which is called leaf nodes may have data or pointers to other indexes key values.

When you search data in B-tree it starts from top to search for values and find the according values. 

In indexes we have two major types of indexes:

Clustered index and nonclustered index.

Clustered Index:

When you create a clustered index on a table than original storage structure will be thrown and it creates b-tree structure. First it sorts data on clustering key value. On leaf node of b-tree it actually stores all rows of data.

So, when you have clustered index on table and you are disabling index you are not able to retrieve any data and you cannot perform any DML operations on that table.

Having multiple clustering index doesn't make any sense. For that reason we have only 1 clustered index per table.

Creating clustered index in sql server
CREATE CLUSTERED INDEX <index-name> on <table-name> (<column-name>)

Nonclustered index:

Non clustered index is much different than clustered index. It sorts data based on your clustering key value and logically stores.

If you already have clustered index on table and you are creating nonclustered index on that table than on the leaf node you have nonclusered key value and pointer to clustered key value.

If you are creating nonclustered index on heap table than its called nonclustered index on heap. In leaf node we have nonclustered key value and pointer to heap row which is also called RID (Row Identifier).

Creating nonclustered index in sql server
CREATE NONCLUSTERED INDEX <index-name> ON <table-name>(<column-name>)

We can have clustered and nonclustered indexes on single or multiple column. Creating indexes on multiple column also known as WIDE index or composite key index.

No comments:

Post a Comment