Clustered Index — Complete Guide
Clustered Index — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of SQL Server Tutorial on Toolliyo Academy.
On this page
SQL Server Tutorial · Lesson 31 of 100
Clustered Index
SQL basics ✓ → Queries → Advanced
Queries · 2 — JOINs · ~6 min · SQL — Indexing & Performance
What is this?
A clustered index defines the physical order of rows in the table. One clustered index per table — often on the primary key. Without one, the table is a heap.
Why should you care?
Range scans on OrderDate or sequential Id lookups are fastest when the clustered key matches how you access data.
See it live — copy this example
Run in SQL Server Management Studio (SSMS) or Azure Data Studio.
USE DataVerse;
IF OBJECT_ID(N'dbo.Invoices', N'U') IS NOT NULL DROP TABLE dbo.Invoices;
CREATE TABLE dbo.Invoices (
InvoiceId INT NOT NULL,
CustomerId INT NOT NULL,
InvoiceDate DATE NOT NULL,
Total DECIMAL(12,2) NOT NULL,
CONSTRAINT PK_Invoices PRIMARY KEY CLUSTERED (InvoiceId)
);
CREATE UNIQUE NONCLUSTERED INDEX UX_Invoices_BizKey
ON dbo.Invoices (CustomerId, InvoiceDate, InvoiceId);
SELECT i.name, i.type_desc
FROM sys.indexes i
WHERE i.object_id = OBJECT_ID(N'dbo.Invoices');
What happened?
- PRIMARY KEY CLUSTERED stores rows in InvoiceId order.
- A separate nonclustered unique index supports business lookups without changing the clustered choice.
Practice next
- Create Invoices and list indexes.
- Insert a few rows and SELECT WHERE InvoiceId = …
- View the estimated plan — should seek on clustered.
- Rebuild: ALTER INDEX PK_Invoices ON dbo.Invoices REBUILD;
- Compare plans for WHERE CustomerId = @id using the NC index.
Remember
Clustered index = row order. Usually the primary key. Choose the key for common access patterns.
Invoice Id lookups
Billing API loads DataVerse invoices by InvoiceId constantly.
Outcome: Clustered PK keeps those gets cheap.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!