Both are B-tree structures that speed up lookups, but they store data differently. Clustered index - Defines the physical (logical) order in which table rows are stored: the leaf level of the index is the data rows themselves. - Only one clustered index per table, because rows can be sorted only one way. - In SQL Server, a PRIMARY KEY creates a clustered index by default (unless one already exists or you specify NONCLUSTERED). - Excellent for range queries and ordered scans on the key (WHERE OrderDate BETWEEN ... ORDER BY OrderDate), and lookups by key. - A table without a clustered index is a heap. Non-clustered index - A separate structure containing the index key columns plus a pointer to the data row: the clustered key (row locator) if the table has a clustered index, or a RID for heaps. - Many non-clustered indexes are allowed per table (up to 999 in SQL Server). - After finding matching keys, SQL Server may need a key lookup into the clustered index to fetch other columns; covering indexes avoid this by including needed columns: CREATE NONCLUSTERED INDEX IX_Orders_CustomerId ON dbo.Orders (CustomerId, OrderDate DESC) INCLUDE (TotalAmount, Status); Comparison - Number per table: one vs many. - Leaf level: data rows vs keys plus row locators. - Storage: no extra copy of data vs additional storage for each index. - Best for: range scans and the main access path vs selective lookups on other columns. Choosing a clustered key Ideally narrow, unique, static (rarely updated) and ever-increasing (an IDENTITY or sequential key) — this keeps all non-clustered indexes small (they store the clustered key) and reduces page splits. Random GUIDs (NEWID()) as clustered keys cause fragmentation; prefer NEWSEQUENTIALID() or a separate identity column. Costs of indexes Every index speeds up reads but slows down INSERT, UPDATE and DELETE and uses storage. Index based on actual query patterns (execution plans, Query Store, missing-index DMVs as hints), and remove unused indexes. Other types worth knowing: filtered indexes, columnstore indexes for analytics, and unique indexes for enforcing constraints.
Ravindra Wadile · · 0 likes