wasAsked.

Indexing Strategy: In what scenarios do you use a clustered index versus a non-clustered index?

QBurst · Role not specified · technical

Published

Year not specified · SQL

Community answers

Posted by wasAsked editorial collection

Clustered index — when to use it - Every table should normally have one clustered index; it defines how rows are stored. - Choose the column that is: - Narrow (small data type, since every non-clustered index stores the clustered key). - Unique (otherwise SQL Server adds a hidden uniquifier). - Static (rarely updated, because changing it moves the row and updates all non-clustered indexes). - Ever-increasing (IDENTITY, sequences or sequential GUIDs) to avoid page splits and fragmentation on inserts. - Usually the primary key surrogate (Id) fits these rules. - Consider clustering on another column when most queries read ranges on it and it still fits the rules reasonably — for example a time-series log table clustered on (CreatedAt, Id) so date-range queries read contiguous pages. - Avoid random GUIDs (NEWID()) as the clustered key on busy tables; use NEWSEQUENTIALID() or keep the GUID as a non-clustered unique key with an identity clustered key. Non-clustered indexes — when to use them - Columns frequently used in WHERE, JOIN, ORDER BY or GROUP BY that are not the clustered key: - Foreign keys (CustomerId on Orders) for joins and lookups. - Search fields (Email, OrderNumber, Status combined with dates). - Composite indexes for common multi-column filters, with the most selective equality columns first and range columns last: (CustomerId, Status, OrderDate). - Covering indexes with INCLUDE for frequent, performance-critical queries, so they avoid key lookups. - Filtered indexes for queries on a small subset (WHERE IsActive = 1, or open orders). - Unique non-clustered indexes to enforce business uniqueness (Email, SKU). When to be careful with non-clustered indexes - Write-heavy tables: each index adds work for every insert and update. - Low-selectivity columns alone (Gender, IsDeleted) rarely help, unless combined with other columns or used as filtered indexes. - Overlapping indexes ((A) and (A, B)) waste space; the wider one often serves both. Process I follow 1. Start with a clustered primary key on a narrow identity column. 2. Add non-clustered indexes for foreign keys and the main query patterns. 3. Use execution plans, Query Store and the missing-index DMVs as guidance (not blindly), then test with realistic data. 4. Review index usage statistics (sys.dm_db_index_usage_stats) periodically and drop unused indexes.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics