Question presented to candidate: "What is the difference between a clustered and a non-clustered index? Why can a table have only one clustered index, what does a non-clustered index actually store, and how does this look in SQL Server, MySQL InnoDB and PostgreSQL?"
What a strong answer should cover:
- A clustered index is the table: its leaf pages hold the full rows, stored in key order, so there can be only one; a non-clustered (secondary) index is a separate structure whose leaves hold the key plus a pointer to the row
- What the pointer is: in SQL Server the clustering key (or a RID on a heap), in InnoDB the primary key, in PostgreSQL a physical tuple address (
ctid); a secondary lookup is therefore two searches on InnoDB and SQL Server clustered tables - Consequences: range scans and
ORDER BYon the clustering key read neighbouring pages; a wide or random clustering key (for example a random UUID) bloats every secondary index and causes page splits - PostgreSQL has no clustered indexes: tables are heaps and every index is secondary;
CLUSTERreorders the table once and is not maintained, and it takes anACCESS EXCLUSIVElock - SQLite: ordinary tables are B-trees keyed by
rowid(anINTEGER PRIMARY KEYis the rowid), andWITHOUT ROWIDtables are clustered on their primary key
Code / implementation expected: Optional β plans or physical row locations that show the difference between a lookup by the clustering key and by a secondary index.
Schema used by the examples: