You can add nonkey columns to the leaf level of the
nonclustered index to by-pass existing index key limits, 900 bytes and
16 key columns, and execute fully covered, indexed, queries. For more
information, see Create Indexes with Included Columns
Index Types
There are two main index types; Clustered index and Non-Clustered index.
A clustered index alters the way that the rows are
stored. When you create a clustered index on a column (or a number of
columns), SQL server sorts the table’s rows by that column(s). It is
like a dictionary, where all words are sorted in alphabetical order in
the entire book. Since it alters the physical storage of the table, only
one clustered index can be created per table. In the above example the
entire rows are sorted by computer_id since a clustered index on computer_id column has been created.
CREATE CLUSTERED INDEX [IX_CLUSTERED_COMPUTER_ID]
ON [dbo].[nics] ([computer_id] ASC)
A non-clustered index, on the other hand, does not
alter the way the rows are stored in the table. It creates a completely
different object within the table that contains the column(s) selected
for indexing and a pointer back to the table’s rows containing the data.
It is like an index in the last pages of a book, where keywords are
sorted and contain the page number to the material of the book for
faster reference. A non-clustered index on the computer_id in the
previous example would look like the table below:
CREATE NONCLUSTERED INDEX [IX_NONCLUSTERED_COMPUTER_ID]
ON [dbo].[nics] ([computer_id] ASC)
Here is the common misconception prevailing in the industry.
Primary Key has to be Clustered Index.
In reality the statement should be corrected as follows:
Primary Key can be Clustered or Non-clustered but it is a common best practice to create a Primary Key as Clustered Index.
Scenario 1 : Primary Key will default to Clustered Index
In this case we will create only Primary
Key and when we check the kind of index created on the table we will
notice that it has created clustered index automatically over it.
-- Case 1 Primary Key Defaults to Clustered Index
USE TempDB
GO
-- Create table
CREATE TABLE TestTable
(ID INT NOT NULL PRIMARY KEY,
Col1 INT NOT NULL)
GO
-- Check Indexes
SELECT OBJECT_NAME(OBJECT_ID) TableObject,
[name] IndexName,
[Type_Desc]
FROM sys.indexes
WHERE OBJECT_NAME(OBJECT_ID) = 'TestTable'
GO
-- Clean up
DROP TABLE TestTable
GO

No comments:
Post a Comment