Indexes in SQL Server
An index is an on-disk structure associated with a table or view that speeds retrieval of rows from the table or view. An index contains keys built from one or more columns in the table or view. These keys are stored in a structure (B-tree) that enables SQL Server to find the row or rows associated with the key values quickly and efficiently.
Types of indexes
A table or view can contain the following types of indexes:
Clustered
Nonclustered
Both clustered and nonclustered indexes can be unique. This means no two rows can have the same value for the index key. Otherwise, the index is not unique and multiple rows can share the same key value.
Indexes and Constraints
Indexes are automatically created when
PRIMARY KEY
and
UNIQUE
constraints are defined on table columns.
For example, when you create a table with a
UNIQUE
constraint, Database Engine automatically creates a nonclustered index.
If you configure a
PRIMARY KEY
, Database Engine automatically creates a clustered index, unless a clustered index already exists.
When you try to enforce a
PRIMARY KEY
constraint on an existing table and a
clustered index already exists on that table, SQL Server enforces the primary key using a nonclustered index.
CREATE INDEX Syntax
Creates an index on a table. Duplicate values are allowed:
CREATE INDEX index_name ON table_name (column1, column2, ...);
CREATE UNIQUE INDEX Syntax
Creates a unique index on a table. Duplicate values are not allowed:
CREATE UNIQUE INDEX index_name ON table_name (column1, column2, ...);