Pages

Thursday, February 7, 2013

Clustered and Non Clustered Indexes

Non-clustered

The data is present in arbitrary order, but the logical ordering is specified by the index.

The data rows may be spread throughout the table regardless of the value of the indexed column or expression.

The non-clustered index tree contains the index keys in sorted order, with the leaf level of the index containing the pointer to the record (page and the row number in the data page in page-organized engines; row offset in file-organized engines).
In a non-clustered index:
  • The physical order of the rows is not the same as the index order.
  • Typically created on non-primary key columns used in JOIN, WHERE, and ORDER BY clauses.
  • Index is stored separately and data is stored separately
  • Data is not determined as a physical order
There can be more than one non-clustered index on a database table.

 Example: Index in a textbook

Non Clustered Index on Salary_grade in following table


Clustered

Clustering alters the data block into a certain distinct order to match the index, resulting in the row data being stored in order. Therefore, only one clustered index can be created on a given database table.

Clustered indices can greatly increase overall speed of retrieval, but usually only where the data is accessed sequentially in the same or reverse order of the clustered index, or when a range of items is selected.

Since the physical records are in this sort order on disk, the next row item in the sequence is immediately before or after the last one, and so fewer data block reads are required.

The primary feature of a clustered index is therefore the ordering of the physical data rows in accordance with the index blocks that point to them. Some databases separate the data and index blocks into separate files, others put two completely different data blocks within the same physical file(s). Create an object where the physical order of rows is the same as the index order of the rows and the bottom (leaf) level of clustered index contains the actual data rows .

 For example Primary Key Constraint in a table no matter if you enter data in an non sequential order it will always be retrieved sequentially as per clustered index

There can be only one Clustered Index in a table how ever there can be more than one columns in a clustered index in a table thus making it into a composite index.

Example: Telephone Directory

Non Clustered index on salary_grade in following table

Salary_grade      Last_Name            First_Name
2                        Timberwood            Jack
2                        Bibleton                   Mike
5                        Rabbies                    Luna

Clustered Index on salary_grade in following table

Salary_grade    Salary
2                       2000
5                       5000

No comments:

Post a Comment