A clustered index in MySQL is a type of index that determines the physical order of data in a table. Each table can have only one clustered index, typically the primary key, which optimizes data retrieval by minimizing disk I/O.
Usage
Clustered indexes are used to enhance the speed of data retrieval operations that involve primary key lookups. They are automatically created when a primary key is defined on a table. If no primary key exists, some storage engines may choose a unique key or an internal row identifier as the clustered index.
CREATETABLEmy_table(
id INTPRIMARYKEY,
name VARCHAR(100));Được hỗ trợ bởi
In this example, the id column serves as the primary key and clustered index, organizing the data in the table based on the id values.
Examples
1. Creating a Table with a Clustered Index
CREATETABLEemployees(
emp_id INTPRIMARYKEY,
emp_name VARCHAR(50));Được hỗ trợ bởi
This example creates an employees table where emp_id is the primary key and acts as the clustered index.
A clustered index in MySQL is a type of index that determines the physical order of data in a table. Each table can have only one clustered index, typically the primary key, which optimizes data retrieval by minimizing disk I/O.
Usage
Clustered indexes are used to enhance the speed of data retrieval operations that involve primary key lookups. They are automatically created when a primary key is defined on a table. If no primary key exists, some storage engines may choose a unique key or an internal row identifier as the clustered index.
In this example, the
idcolumn serves as the primary key and clustered index, organizing the data in the table based on theidvalues.Examples
1. Creating a Table with a Clustered Index
This example creates an
employeestable whereemp_idis the primary key and acts as the clustered index.2. Adding a Clustered Index to an Existing Table
Here, the
order_idcolumn is altered to become the primary key, thus making it the clustered index for theorderstable.3. Viewing Clustered Index Information
This example retrieves information about the clustered index (primary key) of the
employeestable.Performance Implications
Clustered indexes influence various SQL operations as follows:
Clustered indexes can also improve performance for table scanning and sorting operations by reducing the need to sort data explicitly.
Comparison with Non-Clustered Indexes
Tips and Best Practices