Thursday, August 7, 2014

Differences between Clustered and Non-Clustered Indexes

Both Clustered and Nonclustered Indexes have same physical structure in SQL Server. Both are stored as a B-Tree structure in SQL Server.
Below are some characteristics of Clustered Indexes and Nonclustered Indexes in SQL Server.
Clustered Index:
1. The leaf node of a Clustered Index contains data pages of the table on which it is created
2. Clustered Index enforces a logical order on the rows. Rows are ordered based on Clustering Key
3. If the table does not have Clustered Index it is referred to as a "Heap"
4. A Clustered Index always has Index Id of 1
5. A Table can have ONLY 1 Clustered Index
6. A Primary Key constraint creates a Clustered Index by default *
* A Primary Key constraint can also be enforced by Nonclustered Index, You can specify the index type while creating Primary Key

Nonclustered Index:
1. The leaf nodes of a Nonclustered Index consists of Index pages which contain Clustering Key or RID to locate Data Row *
* When Clustered Index is not present leaf node points to Physical Location of the row this is referred to as RID. When a Clustered Index is present this points to Clustering Key (Key column on which Clustered Index is created)
2. Nonclustered Index does not order actual data, It only orders columns present in the Nonclustered Index based on Index Key specified at the time of creation of Nonclustered Index.
3. A table may not have any Nonclustered Indexes
4. Nonclustered Indexes have Index Id > 1
5. Prior to SQL Server 2008 only 249 Nonclustered Indexes can be created. With SQL Server 2008 and above 999 Nonclustered Indexes can be created
6. A Unique Key constraint created a Nonclustered Index by default *
* A Unique Key constraint can also be enforced by Clustered Index, You can specify the index type while creating Unique Key