Indexing Deep Dive

Difficulty: Advanced

Question

What is the difference between a clustered and a non-clustered index? How does each affect query performance?

Answer

A clustered index defines the order in which the table's rows are physically stored: the leaf level of the index is the table data, so a table can have only one. A non-clustered (secondary) index is a separate structure holding the indexed columns plus a pointer back to the row, and a table can have many. Lookups through a clustered index land directly on the data, while a non-clustered index usually needs an extra hop to fetch the remaining columns.

How each is laid out

Both are typically B+trees. The difference is what sits in the leaves:

  • Clustered: leaves contain full rows, sorted by the clustering key. In MySQL InnoDB every table is clustered on its primary key (or the first UNIQUE NOT NULL index, or a hidden 6-byte row ID). In SQL Server you choose the clustered index; by default it is the primary key.
  • Non-clustered: leaves contain the indexed column values plus a row locator. In InnoDB that locator is the primary key value, so a secondary lookup walks the secondary tree, then walks the primary tree. In SQL Server it is the clustering key, or a RID if the table is a heap.

Performance consequences

AspectClusteredNon-clustered
Count per tableOneMany
Leaf contentsEntire rowKey columns + row locator
Range scans on the keyVery fast, rows are contiguousCan mean many random lookups
Extra storageNone beyond the tableSeparate structure per index
Insert costPage splits if keys are not monotonicOne extra tree to maintain per index

Range queries like WHERE created_at BETWEEN ... on a clustered key read neighbouring pages sequentially. The same query through a non-clustered index may do one key lookup per matching row, which is why optimizers often switch to a full scan when a filter matches more than a small fraction of the table.

Covering indexes remove the extra hop

If the non-clustered index contains every column a query needs, the engine answers from the index alone. SQL Server and Postgres (11+) support INCLUDE columns for this; Postgres reports it as an Index Only Scan, MySQL as "Using index" in EXPLAIN.

PostgreSQL is different

Postgres has no true clustered index. Tables are heaps and every index, including the primary key, is secondary and points to a tuple ID (ctid). The CLUSTER command reorders the heap once, but the order is not maintained for new writes. Mentioning this in an interview signals real hands-on experience.

Choosing the clustering key

Pick something narrow, unique, stable and ever-increasing (a BIGINT identity or a time-ordered ID like UUIDv7). Random keys like UUIDv4 cause page splits and fragmentation, and because InnoDB secondary indexes store the primary key, a wide key bloats every index on the table.

Where each index leads you. A non-clustered lookup in InnoDB takes two tree walks unless the index covers the query.
Clustered (InnoDB PK)Secondary index
Tree walk 1Primary key B+treeSecondary B+tree on email
Leaf holdsThe full rowemail + primary key value
Tree walk 2Not neededPrimary key B+tree to fetch row
Skip walk 2 whenAlways skippedIndex covers all selected columns

Code examples

Clustered vs secondary lookups in MySQL

CREATE TABLE users (
  id    BIGINT AUTO_INCREMENT PRIMARY KEY,  -- clustered index
  email VARCHAR(255) NOT NULL,
  name  VARCHAR(100),
  city  VARCHAR(50),
  INDEX idx_email (email),                  -- secondary, stores (email, id)
  INDEX idx_city_name (city, name)          -- secondary, stores (city, name, id)
);

-- One B+tree walk: clustered index leaf is the row
SELECT * FROM users WHERE id = 42;

-- Two walks: idx_email -> id -> clustered index
SELECT * FROM users WHERE email = 'asha@example.com';

-- Covering: answered from idx_city_name alone ("Using index")
EXPLAIN SELECT name, id FROM users WHERE city = 'Pune';

Because InnoDB secondary indexes store the primary key, selecting only indexed columns plus id avoids the second lookup entirely.

Covering index with INCLUDE in PostgreSQL

CREATE INDEX idx_orders_user ON orders (user_id) INCLUDE (status, total_paise);

EXPLAIN SELECT status, total_paise FROM orders WHERE user_id = 7;
-- Index Only Scan using idx_orders_user on orders

INCLUDE columns are stored in the leaf but are not part of the search key, so the query never touches the heap if the visibility map is up to date.

Key points

  • Only one clustered index per table because rows can be physically ordered only one way.
  • InnoDB secondary indexes store the primary key, so a wide PK makes every index bigger.
  • PostgreSQL tables are heaps; all indexes are secondary and CLUSTER is a one-time reorder.
  • Covering indexes avoid the lookup back to the table.
  • Prefer narrow, monotonic clustering keys to avoid page splits.

Common follow-up questions

  • Why can a table have only one clustered index?
  • What is a covering index and how does INCLUDE help?
  • Why do random UUID primary keys hurt InnoDB insert performance?
  • When will the optimizer ignore a non-clustered index and do a full scan?

Interview tips

  • Describe what lives in the leaf nodes; that single detail explains every performance difference.
  • Mention engine differences (InnoDB vs SQL Server vs Postgres) rather than speaking as if all databases behave the same.
  • Bring up covering indexes and EXPLAIN output to show you tune queries in practice.

Concepts covered

Clustered Index, Non-clustered Index, B+Tree, Key Lookup, Covering Index

More Database Design questions