MySQL Indexes
A MySQL index is a data structure used to speed up the speed and performance of database queries.
The establishment of MySQL indexes is important for the efficient operation of MySQL; indexes can greatly improve the retrieval speed of MySQL.
A MySQL index is similar to the index of a book; by storing pointers to data rows, it can quickly locate and access specific data in a table.
For example, if a MySQL with properly designed and used indexes is a Lamborghini, then a MySQL without designed and used indexes is a pedal tricycle.
Take the table of contents (index) page of a Chinese dictionary as an example: we can quickly find the needed character through an index (directory) sorted by pinyin, stroke count, radical, and so on.
Indexes are divided into single-column indexes and composite indexes:
- A single-column index is an index that contains only a single column; a table can have multiple single-column indexes.
- A composite index is an index that contains multiple columns.
When creating an index, you need to ensure that the index is applied to the conditions of the SQL query statement (generally as the conditions of a WHERE clause).
In fact, an index is also a table that stores the primary key and index fields and points to the records of the entity table.
Although indexes can improve query performance, the following points should also be noted:
- Indexes require additional storage space.
- When inserting, updating, and deleting operations on a table, indexes need to be maintained, which may affect performance.
- Too many or unreasonable indexes may lead to performance degradation, so indexes need to be selected and planned carefully.
Normal Index
Indexes can significantly improve query speed, especially when searching in large tables. By using an index, MySQL can directly locate the data rows that satisfy the query conditions without scanning the entire table row by row.
Creating indexes
Use CREATE INDEX The statement can create a normal index.
A normal index is the most common type of index, used to speed up queries on table data.
CREATE INDEX syntax:
CREATE INDEX index_name
ON table_name (column1 [ASC|DESC], column2 [ASC|DESC], ...);
CREATE INDEX: The keyword used to create a normal index.index_name: Specify the name of the index to create. The index name must be unique in the table.table_name: Specify which table to create the index on.(column1, column2, ...): Specify the table column name to index. You can specify one or more columns as a composite index. The data types of these columns are usually numeric, text, or date.ASCandDESC(Optional): Used to specify the sort order of the index. By default, indexes are sorted in ascending order (ASC).
The following example assumes we have a table named students with id, name, and age columns, and we will create a normal index on the name column.
CREATE INDEX idx_name ON students (name);
The above statement will create a normal index named idx_name on the name column of the students table, which will help improve the performance of queries searching by name.
It should be noted that if the table contains a large amount of data, creating the index may take some time, but once created, query performance will be significantly improved.
Modifying Table Structure (Adding Indexes)
We can use the ALTER TABLE The command can create an index on an existing table.
ALTER TABLE allows you to modify the structure of a table, including adding, modifying, or deleting indexes.
ALTER TABLE syntax for creating an index:
ALTER TABLE table_name
ADD INDEX index_name (column1 [ASC|DESC], column2 [ASC|DESC], ...);
ALTER TABLE: The keyword used to modify the table structure.table_name: Specify the name of the table to modify.ADD INDEX: The clause for adding an index.ADD INDEXUsed to create a normal index.index_name: Specify the name of the index to create. The index name must be unique in the table.(column1, column2, ...): Specify the table column name to index. You can specify one or more columns as a composite index. The data types of these columns are usually numeric, text, or date.ASCandDESC(Optional): Used to specify the sort order of the index. By default, indexes are sorted in ascending order (ASC).
The following is an example where we create a normal index on an existing table named employees:
ALTER TABLE employees
ADD INDEX idx_age (age);
The above statement will create a normal index named idx_age on the age column of the employees table.
Specifying Directly When Creating a Table
We can, when creating a table, you can CREATE TABLE specify the index directly in the statement to create the table and index together.
CREATE TABLE table_name (
column1 data_type,
column2 data_type,
...,
INDEX index_name (column1 [ASC|DESC], column2 [ASC|DESC], ...)
);
CREATE TABLE: The keyword used to create a new table.table_name: Specify the name of the table to create.(column1 data_type, column2 data_type, ...): Define the column names and data types of the table. You can specify one or more columns as a composite index. The data types of these columns are usually numeric, text, or date.INDEX: The keyword used to create a normal index.index_name: Specify the name of the index to create. The index name must be unique in the table.(column1, column2, ...): Specify the table column name to index. You can specify one or more columns as a composite index. The data types of these columns are usually numeric, text, or date.ASCandDESC(Optional): Used to specify the sort order of the index. By default, indexes are sorted in ascending order (ASC).
The following is an example where we create a table named students and a normal index on the age column.
CREATE TABLE students (
id INT PRIMARY KEY,
name VARCHAR(50),
age INT,
INDEX idx_age (age)
);
In the above example, we created a normal index named idx_age on the age column of the students table.
Syntax for Deleting an Index
We can use the DROP INDEX The statement to delete an index.
Syntax of DROP INDEX:
DROP INDEX index_name ON table_name;
DROP INDEX: The keyword used to delete an index.index_name: Specify the name of the index to delete.ON table_name: Specify which table to delete the index from.
The syntax for deleting an index using the ALTER TABLE statement is as follows:
ALTER TABLE table_name
DROP INDEX index_name;
ALTER TABLE: The keyword used to modify the table structure.table_name: Specify the name of the table to modify.DROP INDEX: The clause used to delete an index.index_name: Specify the name of the index to delete.
The following example assumes we have a table named employees with an index named idx_age on the age column, and now we want to delete this index:
DROP INDEX idx_age ON employees;
Or use ALTER TABLE Statement:
ALTER TABLE employees
DROP INDEX idx_age;
Both commands will delete the index named idx_age from the employees table.
If the index does not exist, an error will occur when executing the command. Therefore, it is best to confirm whether the index exists before deleting it, or use an error-handling mechanism to deal with possible error situations.
Unique Indexes
In MySQL, you can use the CREATE UNIQUE INDEX statement to create a unique index.
A unique index ensures that the values in the index are unique and does not allow duplicate values.
Creating indexes
CREATE UNIQUE INDEX index_name
ON table_name (column1 [ASC|DESC], column2 [ASC|DESC], ...);
CREATE UNIQUE INDEX: The keyword combination used to create a unique index.index_name: Specify the name of the unique index to create. The index name must be unique in the table.table_name: Specify which table to create the unique index on.(column1, column2, ...): Specify the table column name to index. You can specify one or more columns as a composite index. The data types of these columns are usually numeric, text, or date.ASCandDESC(Optional): Used to specify the sort order of the index. By default, indexes are sorted in ascending order (ASC).
The following is an example of creating a unique index: suppose we have a table named employees with id and email columns, and now we want to create a unique index on the email column to ensure that each employee's email address is unique.
CREATE UNIQUE INDEX idx_email ON employees (email);
The above example will create a unique index named idx_email on the email column of the employees table.
Modifying Table Structure to Add an Index
We can use the ALTER TABLE The command to create a unique index.
ALTER TABLEThe command allows you to modify the structure of an existing table, including adding new indexes.
ALTER table table_name
ADD CONSTRAINT unique_constraint_name UNIQUE (column1, column2, ...);
ALTER TABLE: The keyword used to modify the table structure.table_name: Specify the name of the table to modify.ADD CONSTRAINT: This is the keyword used to add constraints (including unique indexes).unique_constraint_name: Specify the name of the unique index to create; the constraint name must be unique in the table.UNIQUE (column1, column2, ...): Specify the table column name to index. You can specify one or more columns as a composite index. The data types of these columns are usually numeric, text, or date.
The following is an example of using ALTER TABLE An example of creating a unique index with the command: suppose we have a table named employees with id and email columns, and now we want to create a unique index on the email column to ensure that each employee's email address is unique.
ALTER TABLE employees
ADD CONSTRAINT idx_email UNIQUE (email);
The above example will create a unique index named idx_email on the email column of the employees table.
Please note that if the table already contains duplicate email values, adding a unique index will fail. Before creating a unique index, you may need to ensure that the email column in the table has no duplicate values.
Specifying Directly When Creating a Table
We can also, while creating a table, you can CREATE TABLE use the UNIQUE keyword in the statement to create a unique index.
This will define the unique index constraint at the same time the table is created.
CREATE TABLE Syntax for creating a unique index in the statement:
CREATE TABLE table_name (
column1 data_type,
column2 data_type,
...,
CONSTRAINT index_name UNIQUE (column1 [ASC|DESC], column2 [ASC|DESC], ...)
);
CREATE TABLE: The keyword used to create a new table.table_name: Specify the name of the table to create.(column1 data_type, column2 data_type, ...): Define the column names and data types of the table. You can specify one or more columns as a composite index. The data types of these columns are usually numeric, text, or date.CONSTRAINT: The keyword used to add a constraint.index_name: Specify the name of the unique index to create. The constraint name must be unique in the table.UNIQUE (column1, column2, ...): Specify the table column name to index.ASCandDESC(Optional): Used to specify the sort order of the index. By default, indexes are sorted in ascending order (ASC).
The following is an example of creating a unique index when creating a table: suppose we want to create a table named employees with id, name, and email columns, and we want the values in the email column to be unique, so we define a unique index when creating the table.
CREATE TABLE employees (
id INT PRIMARY KEY,
name VARCHAR(50),
email VARCHAR(100) UNIQUE
);
In this example, the email column is defined as a unique index because the UNIQUE keyword is added after it.
Please note that using UNIQUE After the keyword, the index name will be generated automatically, and you can also specify the index name as needed.
Adding and Deleting Indexes with the ALTER Command
There are four ways to add indexes to a data table:
- ALTER TABLE tbl_name ADD PRIMARY KEY (column_list): This statement adds a primary key; the values in the primary key column must be unique, the list of primary key columns can be one or more columns, and cannot contain NULL values. .
- ALTER TABLE tbl_name ADD UNIQUE index_name (column_list): The values of the index created by this statement must be unique (except for NULL, which may appear multiple times).
- ALTER TABLE tbl_name ADD INDEX index_name (column_list): Add a normal index; index values may appear multiple times.
- **ALTER TABLE tbl_name ADD FULLTEXT index_name (column_list):** This statement specifies the index as FULLTEXT, used for full-text indexing.
The following example adds an index to a table.
mysql> ALTER TABLE testalter_tbl ADD INDEX (c);
You can also use the DROP clause in the ALTER command to delete an index. Try the following example to delete an index:
mysql> ALTER TABLE testalter_tbl DROP INDEX c;
Adding and Deleting Primary Keys with the ALTER Command
A primary key acts on columns (it can be a single column or a composite primary key of multiple columns). When adding a primary key, you need to ensure that the primary key is not null by default (NOT NULL). The example is as follows:
mysql> ALTER TABLE testalter_tbl MODIFY i INT NOT NULL;
mysql> ALTER TABLE testalter_tbl ADD PRIMARY KEY (i);
You can also use the ALTER command to delete a primary key:
mysql> ALTER TABLE testalter_tbl DROP PRIMARY KEY;
When deleting a primary key, you only need to specify PRIMARY KEY, but when deleting an index, you must know the index name.
Displaying Index Information
You can use the SHOW INDEX command to list the relevant index information in a table.
You can format the output by adding \G.
SHOW INDEX statement::
mysql> SHOW INDEX FROM table_name\G
........
SHOW INDEX: The keyword used to display index information.FROM table_name: Specify the name of the table whose index information you want to view.\G: Format the output information.
After executing the above command, detailed information about all indexes in the specified table will be displayed, including the index name (Key_name), index column (Column_name), whether it is a unique index (Non_unique), sort order (Collation), index cardinality (Cardinality), and so on.