Sobes.tech
Junior — Middle

Can you explain how a clustered index works in a database?

sobes.tech AI

Answer from AI

A clustered index in a database is a data structure that determines the physical order of storing table rows on disk. Unlike a non-clustered index, where the index and data are stored separately, a clustered index sorts and stores the table data in the order of the index key.

Key points:

  • A table can have only one clustered index, as data can be physically sorted by only one key.
  • Queries with conditions on the clustered index are faster because the data is already ordered.
  • Changing the values of the clustered index key can be an expensive operation, as it requires restructuring the storage order.

Example: if you have a table with orders, and the clustered index is built on the order date, then the records on disk will be stored in date order, which speeds up range queries by date.