Clustered Indexes in SQL Server 2008
An index can be defined using one or more columns in the table, the index key, with the following restrictions:
You can define an index with up to 16 columns
The maximum size of the index key is 900 bytes
The column(s) defined for the clustered index are referred to as the clustering key. A clustered index is special because it causes SQL Server to order the data in the table according to the clustering key. Because a table cannot be sorted more than one way, you can define only one clustered index on a table.
Note
The general syntax for creating a relational index is as follows:
CREATE [ UNIQUE ] [ CLUSTERED | NONCLUSTERED ] INDEX index_name
ON
You may recall the table creation scripts that we used in Article, “Designing Tables,” had a keyword of “clustered” in the specification of a primary key. Although a primary key is a constraint, SQL Server physically implements a primary key as an index. Because the default option for a primary key is clustered, SQL Server creates a clustered index for a primary key. Likewise, a unique constraint is physically implemented as a unique index. Since a primary key is also unique, by default, SQL Server physically implements each primary key as a unique, clustered index.
Note
In the practice that follows, you will create clustered indexes on the OrderHeader and OrderDetail tables previously created in article "Designing Tables". Since we have already created primary keys on the OrderHeader and OrderDetail tables using the default options, you will first drop and re-create the primary keys as nonclustered in order to create the single, allowed clustered index on the table.
Create a Clustered Index
1. |
Execute the following code against the SQL2008SBS database:-Must drop foreign key first, because it depends on the primary keyALTER TABLE Orders. |
2. |
In the Object Explorer, expand the Indexes node for the OrderHeader and OrderDetail tables. Observe that you now have a clustered index along with a unique, nonclustered index created against the table. |