RadhaPublication
HomeInterviewLearning PathsRole TracksMockBooksPricing
Login / Sign UpLog in

© 2026 Radha Publication. All rights reserved.

Shop on AmazonDonateContactPrivacyTerms
SQL questions
MediumSQL#1167 min readJul 11, 2026

Clustered Index

practice
learning
Practice modeTest yourself instead of reading straight through

Why interviewers love this topic: it shows whether you understand how a table is stored, not just how to write a query.

Question: What is a clustered index?

Answer: A clustered index is the index that defines the order of the rows in the table. In SQL Server, the leaf level of a clustered index contains the actual table data, not a separate copy. Because one table can only be stored in one order, SQL Server allows only one clustered index per table.

Interview-Ready Answer: I think of a clustered index as the table’s main sorted structure. In SQL Server, the data rows live at the leaf level of that index, so range searches and ordered reads are fast. A table can have only one clustered index, and I usually want it on a narrow, unique, and mostly increasing key because that keeps reads efficient without making inserts too expensive.

🧠 Memory Map
Memory map — visual summary of this topic

What it is

A clustered index is like the table itself being arranged by one chosen key. A B-tree (balanced tree) is the structure behind it: root page at the top, branch pages in the middle, and leaf pages at the bottom. In SQL Server, the clustered index leaf level holds the real rows; if there is no clustered index, the table is a heap, meaning rows have no ordered structure.

How it works under the hood

  1. When you create a clustered index, SQL Server sorts the rows by the clustered key and builds the B-tree pages.
  2. For a lookup, the engine starts at the root page, follows the branch pages, and lands on the correct leaf page. Because the tree stays balanced, the number of hops stays small even as the table grows.
  3. For a range query like OrderID BETWEEN 100 AND 200, the engine can walk through adjacent leaf pages in key order instead of jumping around the table.
  4. For an insert, SQL Server finds the right leaf page. If the page is full, it may split the page into two pages, which creates extra I/O and can add fragmentation.
  5. If the clustered key changes, the row may need to move to a different page. That is why mutable clustered keys are expensive.

When and why to use it

  • Use a clustered index on columns that are searched by range, sorting, or grouping.
  • Choose a key that is narrow, unique if possible, and stable over time.
  • Good examples are an identity column, a time-ordered key, or a composite key used in date-range reporting.
  • Avoid random or frequently updated keys if the table gets many inserts or updates.

Clustered vs nonclustered vs heap

StructureLeaf levelBest forMain cost
Clustered indexReal rowsRange and orderPage splits
Nonclustered indexKeys + locatorPoint lookupsExtra storage
HeapUnordered rowsRarely usedScans

Here, the locator means the pointer used to reach the row. In a clustered table, nonclustered indexes store the clustered key as that locator, so a wide clustered key makes every nonclustered index wider too.

Performance notes and gotchas

Seek cost is usually O(log n), where n is row count, because the tree height stays small. A range read is closer to O(log n + k), where k is the number of rows returned. In real systems, even a table with 10 million rows often takes only 3 to 5 page hops to reach the right leaf page, but a bad key can create many page splits and slow writes dramatically. Important edge cases: SQL Server can allow duplicate clustered keys if the index is not unique; when duplicates exist, it adds a hidden uniquifier for those rows. A PRIMARY KEY is different: it enforces uniqueness. Also, a clustered index is not the same as permanent physical disk order; pages can move during splits or rebuilds. By default in SQL Server, a primary key becomes clustered unless a clustered index already exists or you specify otherwise. Other engines differ, so always answer in the context of the database being discussed.

Memory rule: the clustered index is the table’s filing cabinet; the nonclustered index is the card catalog that points into it.

Real-world story

Imagine a checkout service for an online store. The Orders table gets thousands of inserts per minute, and support often looks up orders by OrderID or by recent date ranges. The team clusters the table on OrderID, which is narrow, unique, and increasing, so inserts are cheap and support queries can jump straight to the right rows.

Now imagine someone changes the clustered key to CustomerEmail because they think email searches are common. That looks convenient at first, but emails change, inserts become random, and the table starts splitting pages all over the place. The production symptom is easy to spot: checkout latency climbs, the database shows more write I/O and fragmentation, and the logs show slower inserts during busy hours. Users feel it as timeouts or a sluggish order confirmation page. The fix is usually to cluster on the stable business key, keep email as a nonclustered index, and add a covering index only for the specific read pattern that needs it.

SQL
USE tempdb;
GO

IF OBJECT_ID('dbo.ClusteredIndexDemo', 'U') IS NOT NULL
    DROP TABLE dbo.ClusteredIndexDemo;
GO

CREATE TABLE dbo.ClusteredIndexDemo
(
    OrderID    INT NOT NULL,
    CustomerID INT NOT NULL,
    OrderDate  DATE NOT NULL,
    Status     VARCHAR(20) NOT NULL,
    Amount     DECIMAL(10,2) NOT NULL,
    CONSTRAINT PK_ClusteredIndexDemo PRIMARY KEY CLUSTERED (OrderID)
);
GO

-- A nonclustered index is useful when the query filters by a different column.
-- The clustered key is still used to reach the actual row, so keep it narrow.
CREATE NONCLUSTERED INDEX IX_ClusteredIndexDemo_Status
ON dbo.ClusteredIndexDemo (Status);
GO

-- Insert rows out of order on purpose.
-- The clustered index organizes the data by OrderID, not by insert sequence.
INSERT INTO dbo.ClusteredIndexDemo (OrderID, CustomerID, OrderDate, Status, Amount)
VALUES
(105, 2, '2024-01-05', 'New', 19.99),
(101, 1, '2024-01-01', 'Paid', 49.50),
(103, 3, '2024-01-03', 'Shipped', 12.00),
(104, 4, '2024-01-04', 'Cancelled', 99.00),
(102, 1, '2024-01-02', 'Paid', 25.00);
GO

-- Range query on the clustered key: this is the classic strength of clustering.
SELECT OrderID, CustomerID, OrderDate, Status, Amount
FROM dbo.ClusteredIndexDemo
WHERE OrderID BETWEEN 102 AND 104
ORDER BY OrderID;
GO

-- Search on another column: the nonclustered index helps avoid scanning every row.
SELECT OrderID, Status, Amount
FROM dbo.ClusteredIndexDemo
WHERE Status = 'Paid'
ORDER BY OrderID;
GO

-- Failure path: this fails because PRIMARY KEY enforces uniqueness.
-- Important nuance: a clustered index can be non-unique, but a primary key cannot.
BEGIN TRY
    INSERT INTO dbo.ClusteredIndexDemo (OrderID, CustomerID, OrderDate, Status, Amount)
    VALUES (102, 9, '2024-01-06', 'New', 10.00);
END TRY
BEGIN CATCH
    SELECT
        ERROR_NUMBER() AS ErrorNumber,
        ERROR_MESSAGE() AS ErrorMessage;
END CATCH;
GO

Follow-up & Tricky Questions

  • Why can a table have only one clustered index? Because the clustered index defines the row order of the table itself, and the data can only be arranged one way at a time.
  • What is the difference between clustered and nonclustered indexes? A clustered index stores the actual rows at the leaf level, while a nonclustered index stores key values plus a row locator that points to the data.
  • What happens when the clustered key changes? SQL Server may have to move the row to a different page and update every nonclustered index that stores that key, which makes updates more expensive.
  • How does a clustered index affect nonclustered indexes? It becomes the locator used by nonclustered indexes, so a wide clustered key makes all nonclustered indexes wider and slower.
  • When would you choose a heap instead? Rarely, but sometimes for staging tables or write-heavy temporary loads where you do not need ordered access and will add indexes later.
  • Does a clustered index mean the data is physically sorted forever? No. It means the logical order follows the key; page splits, deletes, and rebuilds can change physical page placement.
  • Can a clustered index have duplicate values? Yes, the index itself can be non-unique, and SQL Server adds a hidden uniquifier when needed; a primary key is the thing that enforces uniqueness.
  • Is a clustered index always the fastest choice? No. It is best for range and ordered access, but a poor key can hurt insert speed and make every nonclustered index heavier.

Common Mistakes

  • Choosing a random GUID as the clustered key: this causes page splits and fragmentation; use a narrower, more sequential key if possible.
  • Thinking clustered means always faster: clustered indexes are great for range reads, but they can slow inserts and updates when the key is bad.
  • Forgetting the impact on nonclustered indexes: every nonclustered index carries the clustered key, so a wide clustered key increases storage and I/O.
  • Assuming physical disk order never changes: row order is logical, not a promise about where pages sit on disk forever.

Memory Hook: Think of a clustered index as the shelf itself, not the sticky note on the shelf. The table is stored in that order; the nonclustered index is the note that points you to the shelf.

Cheat Sheet:

  • One clustered index per table in SQL Server.
  • Leaf level = actual table rows.
  • Best for range filters, sorting, and ordered scans.
  • Bad clustered keys hurt inserts and updates.
  • Keep the clustered key narrow, stable, and usually unique.
  • Nonclustered indexes store the clustered key as the row locator.

Practice Tasks:

  • Create a table with a clustered primary key and run a range query on that key.
  • Change the clustered key to a random GUID in a test table and compare insert speed and fragmentation.
  • Add a nonclustered index on a search column and compare query behavior before and after.
Previous
Back to Questions←→to navigate
Next

Recommended Resources

Recommended Book

Cracking the Coding Interview

189 Programming Questions and Solutions

Recommended Book

Cracking the Coding Interview

189 Programming Questions and Solutions

USE tempdb; GO IF OBJECT_ID('dbo.ClusteredIndexDemo', 'U') IS NOT NULL DROP TABLE dbo.ClusteredIndexDemo; GO CREATE TABLE dbo.ClusteredIndexDemo ( OrderID INT NOT NULL, CustomerID INT NOT NULL, OrderDate DATE NOT NULL, Status VARCHAR(20) NOT NULL, Amount DECIMAL(10,2) NOT NULL, CONSTRAINT PK_ClusteredIndexDemo PRIMARY KEY CLUSTERED (OrderID) ); GO -- A nonclustered index is useful when the query filters by a different column. -- The clustered key is still used to reach the actual row, so keep it narrow. CREATE NONCLUSTERED INDEX IX_ClusteredIndexDemo_Status ON dbo.ClusteredIndexDemo (Status); GO -- Insert rows out of order on purpose. -- The clustered index organizes the data by OrderID, not by insert sequence. INSERT INTO dbo.ClusteredIndexDemo (OrderID, CustomerID, OrderDate, Status, Amount) VALUES (105, 2, '2024-01-05', 'New', 19.99), (101, 1, '2024-01-01', 'Paid', 49.50), (103, 3, '2024-01-03', 'Shipped', 12.00), (104, 4, '2024-01-04', 'Cancelled', 99.00), (102, 1, '2024-01-02', 'Paid', 25.00); GO -- Range query on the clustered key: this is the classic strength of clustering. SELECT OrderID, CustomerID, OrderDate, Status, Amount FROM dbo.ClusteredIndexDemo WHERE OrderID BETWEEN 102 AND 104 ORDER BY OrderID; GO -- Search on another column: the nonclustered index helps avoid scanning every row. SELECT OrderID, Status, Amount FROM dbo.ClusteredIndexDemo WHERE Status = 'Paid' ORDER BY OrderID; GO -- Failure path: this fails because PRIMARY KEY enforces uniqueness. -- Important nuance: a clustered index can be non-unique, but a primary key cannot. BEGIN TRY INSERT INTO dbo.ClusteredIndexDemo (OrderID, CustomerID, OrderDate, Status, Amount) VALUES (102, 9, '2024-01-06', 'New', 10.00); END TRY BEGIN CATCH SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage; END CATCH; GO