In SQL Server, an index is a database structure that is used to improve the performance of queries by allowing faster access to data. There are two main types of indexes, clustered and non-clustered.
A clustered index determines the physical order of data in a table. It is created on a single column or a group of columns called a key. When a table has a clustered index, the data is ordered by the key values and physically stored in the same order on disk. There can be only one clustered index per table.
A non-clustered index is a separate structure from the data and is used to improve the performance of queries by allowing faster access to data. It is also created on one or more columns called key columns. A non-clustered index contains a copy of the data in the indexed columns and a pointer to the location of the full data row in the table. There can be multiple non-clustered indexes per table.
The main difference between a clustered and non-clustered index is the order of the data. In a clustered index, the physical order of the data on disk matches the order of the key columns in the index. In a non-clustered index, the physical order of the data on disk is not related to the order of the key columns in the index.
Another difference between the two types of indexes is the impact on performance. A clustered index can greatly improve the performance of queries that involve range searches or sorting based on the key column(s) in the index. Since the data is physically ordered on disk, SQL Server can retrieve the rows more efficiently. However, a clustered index can also slow down insert and update operations, since SQL Server needs to rearrange the data to maintain the physical order of the index.
On the other hand, a non-clustered index can improve the performance of queries that filter data based on the indexed columns, but it may not be as efficient for range searches or sorting. Non-clustered indexes can also speed up data modification operations, since they don’t require any rearrangement of the data.
Here is an example of creating a clustered index on the "ID" column of a table:
CREATE CLUSTERED INDEX IX_MyTable_ID ON dbo.MyTable (ID);
And here is an example of creating a non-clustered index on the "LastName" and "FirstName" columns of a table:
CREATE NONCLUSTERED INDEX IX_MyTable_Name
ON dbo.MyTable (LastName, FirstName);
In summary, a clustered index determines the physical order of data in a table based on its key column(s), while a non-clustered index is a separate structure that contains a copy of the indexed columns and a pointer to the location of the full data row in the table. The choice of index type depends on the specific query patterns and data modification requirements of your application.