Create Indexes

Indexes are special lookup tables that the database search engine can use to speed up data retrieval operations. An index is a data structure that improves the speed of data retrieval operations on a database table at the cost of additional write operations, which are used to maintain the data structure. Indexes can also be used to enforce uniqueness.

Types of Indexes

SQL Server supports several types of indexes, including:

Creating an Index

You can create an index using the CREATE INDEX Transact-SQL statement.

Syntax

CREATE [ UNIQUE ] [ CLUSTERED | NONCLUSTERED ] INDEX index_name
ON schema_name.table_name ( column1 [ ASC | DESC ] [ , column2 [ ASC | DESC ] ... ] )
[ INCLUDE ( column3 [ , column4 ] ... ) ]
[ WITH ( option1 = value1 [ , option2 = value2 ] ... ) ]
[ ; ]

Example: Creating a Nonclustered Index

Sample Code

-- Create a nonclustered index on the 'LastName' column of the 'Customers' table
CREATE NONCLUSTERED INDEX IX_Customers_LastName
ON dbo.Customers (LastName ASC);

Example: Creating a Clustered Index

Sample Code

-- Create a clustered index on the 'CustomerID' column of the 'Orders' table
CREATE CLUSTERED INDEX PK_Orders_CustomerID
ON dbo.Orders (CustomerID);

Example: Creating a Unique Index

Sample Code

-- Create a unique index on the 'Email' column to ensure unique email addresses
CREATE UNIQUE NONCLUSTERED INDEX UQ_Users_Email
ON dbo.Users (Email);

Example: Creating a Filtered Index

Sample Code

-- Create a filtered index for active customers
CREATE NONCLUSTERED INDEX IX_Customers_Active
ON dbo.Customers (CustomerID)
WHERE IsActive = 1;

Index Options

The WITH clause allows you to specify various options that affect how the index is created and maintained, such as:

Note: Indexes can significantly improve query performance, but they also add overhead to data modification operations (INSERT, UPDATE, DELETE). It's crucial to choose the right columns for indexing and to monitor index usage and fragmentation.

Index Maintenance

Regular maintenance of indexes is important to ensure optimal performance. This includes:

You can manage indexes using SQL Server Management Studio (SSMS) or Transact-SQL commands like ALTER INDEX.

Example: Rebuilding an Index

Sample Code

ALTER INDEX IX_Customers_LastName ON dbo.Customers REBUILD;

Example: Reorganizing an Index

Sample Code

ALTER INDEX IX_Customers_LastName ON dbo.Customers REORGANIZE;

When to Use Indexes

Indexes are most beneficial for:

Avoid creating indexes on columns with very low cardinality (few distinct values) or on tables with high write activity unless absolutely necessary.