Database.Middle.What are the differences between clustered and non-clustered indexes?

🔹 Clustered Index

FeatureDescription
Data StoragePhysically reorders the table’s rows to match the index. The index is the table.
Only OneA table can have only one clustered index because data rows can be sorted in only one order.
Faster for Range QueriesIdeal for queries that return a range of values (e.g. BETWEEN, ORDER BY, GROUP BY) because data is stored in order.
Primary Key by DefaultIn many databases, the primary key automatically becomes the clustered index (unless specified otherwise).
Example UseIndexing customer_id in a Customers table for fast lookup and sorting by ID.

🔹 Non-Clustered Index

FeatureDescription
Separate from DataStores a copy of indexed columns and a pointer to the actual data row. The data remains in the original order.
Multiple AllowedA table can have many non-clustered indexes (limited by DBMS).
Slower for Range QueriesLess efficient for large range scans due to extra lookup steps (called bookmark lookups or key lookups).
FlexibleCan be created on any column(s), useful for filtering or joining on non-primary fields.
Example UseIndexing 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

AspectClustered IndexNon-Clustered Index
Physical order of dataMatches indexUnchanged
Number per tableOneMany
Speed for range queriesFasterSlower
Points to data?Is the dataPoints to data
Ideal forSorting, range filtersLookups on non-key columns
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.