Clustered vs Non-Clustered Index

Indexes are critical in databases for improving the speed of data retrieval. Understanding the difference between clustered and non-clustered indexes helps in optimizing database performance.

Clustered Index

A clustered index determines the physical order of data in a table. This means the table’s rows are stored on disk in the same order as the index. Each table can have only one clustered index because the data rows themselves can only be sorted in one order.

Key Points:

  • Sorts and stores the actual data rows in the index order.
  • Improves performance for range queries or queries that retrieve a series of records in order.
  • Example: If a table has a clustered index on CustomerID, the rows are physically stored in ascending order of CustomerID.

Pros:

  • Fast retrieval of records for range-based queries.
  • Reduces I/O when accessing consecutive rows.

Cons:

  • Slower insert, update, and delete operations because rows may need to be moved to maintain order.
  • Only one clustered index is allowed per table.

Non-Clustered Index

A non-clustered index creates a separate structure that stores index keys and a pointer to the actual data rows. The data itself is not sorted according to this index, allowing multiple non-clustered indexes per table.

Key Points:

  • Does not affect the physical order of the table.
  • Contains index keys and pointers to the data location.
  • Ideal for queries searching specific values or columns that are frequently filtered.
  • Example: A non-clustered index on Email allows quick search of a customer by email without reordering the data rows.

Pros:

  • Multiple non-clustered indexes can exist on a single table.
  • Speeds up lookups and queries on columns that are not part of the clustered index.

Cons:

  • Requires extra storage space.
  • Slightly slower for insert, update, and delete operations due to maintaining the index structure.

Summary

FeatureClustered IndexNon-Clustered Index
Physical order of dataYesNo
Number allowed per table1Multiple
Best useRange queriesSearch queries on specific columns
Data storageData rows sortedIndex structure points to data rows

Understanding when to use clustered versus non-clustered indexes is key to database optimization. Use clustered indexes for primary keys and frequently sorted columns, and non-clustered indexes for columns often used in search and filtering.

Home » Intermediate SQL for Data Professionals (SQL-201) > What is an Index? > Clustered vs Non-Clustered Index