Explain the differences between clustered and non-clustered indexes.

Instruction: Describe the key differences and use cases for each type of index.

Context: This question assesses the candidate's understanding of SQL indexes and their ability to distinguish between clustered and non-clustered indexes, which is crucial for optimizing database performance.

Updated

Official answer

For SQL Server rowstore indexes, the clustered index's leaf level contains the table's data rows organized by the clustered key. A table can have one such clustered index; without one it is a heap. This describes logical index organization, not a promise that every row sits contiguously on disk or a SELECT will return sorted output.

A nonclustered index is a separate structure with key values and row locators, optionally including other columns. A locator can be the clustered key or a heap row identifier, depending on the table. Multiple nonclustered indexes can support different access patterns.

Choose a stable, appropriately narrow clustered key and useful nonclustered keys from the workload. Range access or covered queries can benefit, while inserts and changes may require maintenance, logging, page splits or extra lookups. Nonclustered indexes are not automatically cheap to update, and a wide clustered key can increase their size.

Measure representative plans and write costs. PostgreSQL CLUSTER and other engines' storage organizations have different semantics; do not apply SQL Server rules universally.

Reference: SQL Server clustered and nonclustered indexes.

Related Questions