🔹 Clustered Index
Feature | Description |
---|---|
Data Storage | Physically reorders the table’s rows to match the index. The index is the table. |
Only One | A table can have only one clustered index because data rows can be sorted in only one order. |
Faster for Range Queries | Ideal for queries that return a range of values (e.g. BETWEEN , ORDER BY , GROUP BY ) because data is stored in order. |
Primary Key by Default | In many databases, the primary key automatically becomes the clustered index (unless specified otherwise). |
Example Use | Indexing customer_id in a Customers table for fast lookup and sorting by ID. |
🔹 Non-Clustered Index
Feature | Description |
---|---|
Separate from Data | Stores a copy of indexed columns and a pointer to the actual data row. The data remains in the original order. |
Multiple Allowed | A table can have many non-clustered indexes (limited by DBMS). |
Slower for Range Queries | Less efficient for large range scans due to extra lookup steps (called bookmark lookups or key lookups). |
Flexible | Can be created on any column(s), useful for filtering or joining on non-primary fields. |
Example Use | Indexing the email column in a Users table to speed up login queries. |
🧠 Quick Analogy
- Clustered index: Like a sorted dictionary, where entries are arranged by the word itself.
- Non-clustered index: Like the index at the back of a textbook, pointing you to page numbers (locations of data).
✅ Summary Table
Aspect | Clustered Index | Non-Clustered Index |
---|---|---|
Physical order of data | Matches index | Unchanged |
Number per table | One | Many |
Speed for range queries | Faster | Slower |
Points to data? | Is the data | Points to data |
Ideal for | Sorting, range filters | Lookups on non-key columns |