mysql
  1. mysql-clustered-vs-non-clustered-index

Clustered vs Non-Clustered Index - (MySQL Indexes)

In MySQL, indexes are used to improve the performance of queries by allowing the database to quickly find the data it needs. There are two types of indexes in MySQL: clustered and non-clustered. In this tutorial, we'll explore the differences between these two types of indexes.

Syntax

Creating an index in MySQL is simple. Here's the syntax:

CREATE [UNIQUE] INDEX index_name
ON table_name (column1, column2, ...);

You can create a clustered or non-clustered index by adding the CLUSTERED or NONCLUSTERED keyword after the CREATE keyword. However, keep in mind that MySQL does not support clustered indexes explicitly, so it will treat the CLUSTERED keyword as a regular non-clustered index.

Example

Here's an example of creating a non-clustered index on a MySQL table:

CREATE INDEX idx_user_email
ON users (email);

Explanation

In MySQL, a clustered index determines the physical order of the data in a table, while a non-clustered index does not. With a clustered index, the database sorts the data according to the values in the index. As a result, when you query the data based on the index, the query will be faster because the database can read the data sequentially.

Use

Use clustered indexes when you need to retrieve many rows of data in order, or when you need to update, insert, or delete large amounts of data. The clustered index will help the database maintain the correct physical order of the data.

Use non-clustered indexes when you need to find data based on a specific column or set of columns. Non-clustered indexes help the database quickly locate the data that matches your query.

Important Points

  • Clustered indexes determine the physical order of the data in a table.
  • Non-clustered indexes do not affect the physical order of the data in a table.
  • Clustered indexes are best used for tables that have many rows of data, while non-clustered indexes are best used for tables that have a smaller amount of data.
  • In MySQL, the CLUSTERED keyword has the same effect as the NONCLUSTERED keyword.

Summary

In this tutorial, we explored the differences between clustered and non-clustered indexes in MySQL. We covered the syntax, example, explanation, use, and important points of each type of index. Understanding the differences between these types of indexes can help you choose the best one for your MySQL database and optimize your queries for better performance.

Published on: