mysql add index how does mysql create an index

  • 2020-05-14 05:05:35
  • OfStack

1. Add PRIMARY KEY (primary key index)
mysql > ALTER TABLE `table_name` ADD PRIMARY KEY ( `column` )
2. Add UNIQUE(exclusive index)
mysql > ALTER TABLE `table_name` ADD UNIQUE (
`column`
)
3. Add INDEX(normal index)
mysql > ALTER TABLE `table_name` ADD INDEX index_name ( `column` )
4. Add FULLTEXT(full-text index)
mysql > ALTER TABLE `table_name` ADD FULLTEXT ( `column`)
5. Add multi-column indexes
mysql > ALTER TABLE `table_name` ADD INDEX index_name ( `column1`, `column2`, `column3` )

Here's a more detailed approach

The alter table statement can be used in MySQL to add indexes to fields in the table.

The basic syntax for adding an index to a field in a table using the alter table statement is:
ALTER TABLE < The name of the table > ADD INDEX ( < field > );

Let's try to add an index to the t_name field in test.

mysql > alter table test add index(t_name);
Query OK, 0 rows affected (0.17 sec)
Records: 0 Duplicates: 0 Warnings: 0

After a successful execution, let's look at the results.

mysql > describe test;
+------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+-------------+------+-----+---------+-------+
| t_id | int(11) | YES | | NULL | |
| t_name | varchar(50) | NO | MUL | NULL | |
| t_password | char(32) | YES | | NULL | |
| t_birth | date | YES | | NULL | |
+------------+-------------+------+-----+---------+-------+
4 rows in set (0.00 sec)

As a result, the Key 1 column of the t_name field has changed from white space to MUL. What does MUL mean? Simple explanation 1: if Key is MUL, then the value of the column can be repeated, either as the leading column of a non-exclusive index (column 1) or as part of a unique index but can contain the null value NULL.

MySQL USES SQL statement to add indexes to the fields in the table. Thanks!


Related articles: