Indexes
Indexes
Section titled βIndexesβWhat it means
Section titled βWhat it meansβAn index is a separate, ordered data structure SQL Server maintains alongside a table, letting it find matching rows quickly (like a bookβs index) instead of scanning every row. A tableβs PRIMARY KEY creates a clustered index automatically (the tableβs rows are physically ordered by it β there can only be one per table). You can add nonclustered indexes on other columns you frequently filter or sort by.
Examples
Section titled βExamplesβ-- Nonclustered index on a column you frequently filter byCREATE INDEX IX_Orders_CustomerId ON Orders (CustomerId);
-- Composite index -- speeds up queries filtering on both columns togetherCREATE INDEX IX_Orders_CustomerId_OrderDate ON Orders (CustomerId, OrderDate);
-- Unique index -- also enforces uniqueness, like a UNIQUE constraintCREATE UNIQUE INDEX IX_Customers_Email ON Customers (Email);
-- See what indexes exist on a tableEXEC sp_helpindex 'Orders';
-- Check whether a query actually uses an index (via execution plan tools)SELECT * FROM Orders WHERE CustomerId = 42; -- fast with IX_Orders_CustomerIdCommon mistake
Section titled βCommon mistakeβAdding indexes to every column βjust in caseβ β indexes speed up reads but slow down every INSERT/UPDATE/DELETE, since SQL Server must maintain each index in sync with every write. Over-indexing a write-heavy table can hurt overall performance more than it helps.
-- Adding indexes on rarely-queried columns adds write overhead for no read benefitCREATE INDEX IX_Orders_InternalNotes ON Orders (InternalNotes); -- probably never filtered on
-- Better: index only columns actually used in WHERE, JOIN, and ORDER BY clauses,-- based on real query patterns -- not speculatively on everythingQuick practice
Section titled βQuick practiceβ-
Whatβs the difference between a clustered and a nonclustered index?
Answer
A clustered index determines the physical storage order of the table's rows (only one per table, usually the primary key); a nonclustered index is a separate structure pointing back to the rows, and a table can have many. -
Why isnβt it a good idea to add an index on every column?
Answer
Every index must be updated on everyINSERT/UPDATE/DELETE, so excessive indexing slows down writes for read benefits that may never materialize if that column is rarely queried. -
What kind of query pattern benefits most from adding an index on a column?
Answer
Columns frequently used inWHEREfilters,JOINconditions, orORDER BYclauses, especially on large tables.