What is the difference between a clustered and a non-clustered index?
MediumConceptIndexing & Query Optimization
Answer
A clustered index decides the physical order in which a table's rows are stored: its leaf level contains the rows themselves. A non-clustered (secondary) index is a separate structure whose leaves hold the indexed values and a pointer to each row.
- A table can have only one clustered index, because rows can be stored in only one order, but it can have many non-clustered indexes.
- In MySQL InnoDB, the primary key is the clustered index, and secondary indexes store the primary key as their pointer, so a secondary lookup may need a second search in the clustered index.
- SQL Server makes the primary key clustered by default. PostgreSQL stores tables as unordered heaps, so all of its indexes are non-clustered; its
CLUSTERcommand reorders a table only once. - A non-clustered index that contains every column a query needs is a covering index and avoids the extra lookup.
Example: A telephone directory sorted by surname is like a clustered index: the entries themselves are in order. The index at the back of a textbook is like a non-clustered index: it lists topics alphabetically, with page numbers that point to the actual content.
More in Indexing & Query Optimization
| # | Problem | Platform | Difficulty | Open | 1st1st Visit | 2nd2nd Visit | RevRevise |
|---|---|---|---|---|---|---|---|
| 1 | What is indexing in DBMS, and why does it make queries faster? | Concept | Easy | Read the answer to What is indexing in DBMS, and why does it make queries faster? | |||
| 2 | What is the difference between a B tree and a B+ tree? | Concept | Medium | Read the answer to What is the difference between a B tree and a B+ tree? | |||
| 3 | What is the difference between a clustered and a non-clustered index? | Concept | Medium | Read the answer to What is the difference between a clustered and a non-clustered index? | |||
| 4 | What is the difference between a dense index and a sparse index? | Concept | Medium | Read the answer to What is the difference between a dense index and a sparse index? | |||
| 5 | How would you find and fix a slow SQL query? | Concept | Hard | Read the answer to How would you find and fix a slow SQL query? |