MSDN Documentation

Creating Indexes in SQL Server

Indexes are critical for improving query performance in SQL Server. Understanding how to create and manage them is a fundamental skill for database administrators and developers.

What is an Index?

An index is a database structure that improves the speed of data retrieval operations on a table. It works similarly to an index in a book; it contains keys, and for each key, it has a pointer to the row in the table that contains the corresponding key.

Types of Indexes

SQL Server supports several types of indexes, with the most common being:

Creating a Basic Nonclustered Index

The simplest way to create an index is by using the CREATE INDEX statement.


CREATE INDEX IX_CustomerLastName
ON Customers (LastName);
                

This statement creates a nonclustered index named IX_CustomerLastName on the LastName column of the Customers table.

Creating a Clustered Index

A clustered index is typically created on the primary key of a table. If a table has a primary key constraint, SQL Server often automatically creates a clustered index on it. You can also create it explicitly.


-- Assuming CustomerID is the primary key
CREATE CLUSTERED INDEX PK_Customers
ON Customers (CustomerID);
                

Note: If a table already has a clustered index, you cannot create another one.

Creating a Unique Index

A unique index ensures that no duplicate values exist in the indexed column(s).


CREATE UNIQUE INDEX UQ_ProductCode
ON Products (ProductCode);
                

Creating a Composite Index

A composite index includes multiple columns. The order of columns in a composite index is important for query optimization.


CREATE INDEX IX_OrderDateAndCustomerID
ON Orders (OrderDate, CustomerID);
                

Creating a Filtered Index

Filtered indexes can significantly improve performance and reduce index maintenance overhead by indexing only a subset of data.


CREATE NONCLUSTERED INDEX IX_OpenOrders
ON Orders (CustomerID)
WHERE OrderStatus = 'Open';
                

Index Options

The CREATE INDEX statement supports various options, such as:

Best Practices for Indexing

Managing Indexes

You can use the following Transact-SQL statements to manage indexes:

Action Command
Drop an index DROP INDEX index_name ON table_name;
Reorganize an index ALTER INDEX index_name ON table_name REORGANIZE;
Rebuild an index ALTER INDEX index_name ON table_name REBUILD;
View index information sp_helpindex 'table_name'; or query system catalog views like sys.indexes.

Effective index management is crucial for maintaining optimal database performance. Refer to the official SQL Server documentation for advanced techniques and specific scenarios.