MySQL index type overview enables MySQL to run efficiently

Source: Internet
Author: User
Tags mysql index
Index is the key to quick search. The establishment of MySQL indexes is very important for the efficient operation of MySQL. The following describes several common MySQL index types. Index fields in database tables can greatly improve the query speed. Assume that we have created a mytable: CREATETABLEmytable (IDINTNOTNULL, usernameVARCHAR

Index is the key to quick search. The establishment of MySQL indexes is very important for the efficient operation of MySQL. The following describes several common MySQL index types. Index fields in database tables can greatly improve the query speed. Suppose we have created a mytable TABLE: create table mytable (id int not null, username VARCHAR

Index is the key to quick search. The establishment of MySQL indexes is very important for the efficient operation of MySQL. The following describes several common MySQL index types.

Index fields in database tables can greatly improve the query speed. Suppose we have created a mytable table:

 
 
  1. CREATE TABLE mytable(
  2. ID INT NOT NULL,
  3. username VARCHAR(16) NOT NULL
  4. );

We randomly inserted 10000 records, one of which is 5555 and admin.

When querying the record SELECT * FROM mytable WHERE username = 'admin'; of username = "admin", MySQL does not need to perform any scans if an index has been created on username, this record can be found accurately. On the contrary, MySQL scans all records to query 10000 records.

Indexes are divided into single-column indexes and composite indexes. A single-column index contains only one column. A table can have multiple single-column indexes, but this is not a combination index. A composite index contains multiple columns.

MySQL indexes include:

(1) Common Index

This is the most basic index with no restrictions. It can be created in the following ways:

◆ Create an index

 
 
  1. CREATE INDEX indexName ON mytable(username(length));

For CHAR and VARCHAR types, the length can be smaller than the actual length of the field; For BLOB and TEXT types, the length must be specified, the same below.

◆ Modify Table Structure

 
 
  1. ALTER mytable ADD INDEX [indexName] ON (username(length))

◆ When creating a table, specify

 
 
  1. CREATE TABLE mytable(
  2. ID INT NOT NULL,
  3. username VARCHAR(16) NOT NULL,
  4. INDEX [indexName] (username(length))
  5. );

Syntax for deleting an index:

 
 
  1. DROP INDEX [indexName] ON mytable;

(2) unique index

It is similar to the previous normal index. The difference is that the value of the index column must be unique, but null values are allowed. If it is a composite index, the combination of column values must be unique. It can be created in the following ways:

◆ Create an index

 
 
  1. CREATE UNIQUE INDEX indexName ON mytable(username(length))

◆ Modify Table Structure

 
 
  1. ALTER mytable ADD UNIQUE [indexName] ON (username(length))

◆ When creating a table, specify

 
 
  1. CREATE TABLE mytable(
  2. ID INT NOT NULL,
  3. username VARCHAR(16) NOT NULL,
  4. UNIQUE [indexName] (username(length))
  5. );

(3) Primary Key Index

It is a special unique index and does not allow null values. Generally, when creating a table, you can create a primary key index at the same time:

 
 
  1. CREATE TABLE mytable(
  2. ID INT NOT NULL,
  3. username VARCHAR(16) NOT NULL,
  4. PRIMARY KEY(ID)
  5. );

Of course, you can also use the ALTER command. Remember: A table can only have one primary key.

(4) Composite Index

To visually compare Single-Column indexes and composite indexes, add multiple fields to the table:

 
 
  1. CREATE TABLE mytable(
  2. ID INT NOT NULL,
  3. username VARCHAR(16) NOT NULL,
  4. city VARCHAR(50) NOT NULL,
  5. age INT NOT NULL
  6. );

To further extract MySQL efficiency, you must consider establishing a composite index. Create name, city, and age in an index:

 
 
  1. ALTER TABLE mytable ADD INDEX name_city_age (name(10),city,age);

The usernname length is 16 when the table is created, and 10 is used here. This is because the name length generally does not exceed 10, which will accelerate the index query speed, reduce the size of the index file, and increase the INSERT update speed.

If a single column index is created on usernname, city, and age respectively, the table has three single column indexes, and the query efficiency will be significantly different from that of the preceding composite indexes, far lower than our combined index. Although there are three indexes at this time, MySQL can only use one of them, which seems to be the most efficient single-column index.

The establishment of such a composite index is actually equivalent to the establishment of the following three composite indexes:

 
 
  1. usernname,city,age
  2. usernname,city
  3. usernname

Why is there no composite index like city and age? This is because MySQL Composite Index "leftmost prefix" results. A simple understanding is to combine only from the leftmost. This composite index is not used for queries that contain these three columns. The following SQL statements use this composite index:

 
 
  1. SELECT*FROMMytable WHREE username ="Admin" ANDCity ="Zhengzhou"
  2. SELECT*FROMMytable WHREE username ="Admin"

The following are not used:

 
 
  1. SELECT*FROMMytable WHREE age = 20ANDCity ="Zhengzhou"
  2. SELECT*FROMMytable WHREE city ="Zhengzhou"

(5) Time to create an index

Now we have learned how to create an index. Under what circumstances do we need to create an index? IN general, you need to create an index for the columns that appear IN the WHERE and JOIN operations, but this is not the case because MySQL only applies to <, <=, =,>,> =, BETWEEN, IN, and sometimes LIKE will use the index. For example:

 
 
  1. SELECTT.Name
  2. FROMMytable tLEFT JOINMytable m
  3. ONT.Name= M. usernameWHEREM. age = 20ANDM. city ='Zhengzhou'

In this case, you need to create an index for the city and age. Because the userame of the mytable table also appears in the JOIN clause, it is also necessary to create an index for it.

As mentioned earlier, only LIKE needs to be indexed in some cases. MySQL does not use an index when it starts with the wildcard "%" and. For example, the following sentence uses an index:

 
 
  1. SELECT * FROM mytable WHERE username like'admin%'

The following statement will not be used:

 
 
  1. SELECT * FROM mytable WHEREt Name like'%admin'

Therefore, pay attention to the above differences when using LIKE.

(6) index Deficiency

The advantages of using indexes are described above, but excessive use of indexes will cause abuse. Therefore, the index also has its disadvantages:

◆ Although the index greatly improves the query speed, it also reduces the speed of updating tables, such as performing INSERT, UPDATE, and DELETE operations on tables. When updating a table, MySQL not only needs to save data, but also stores the index file.

◆ Index files that occupy disk space when an index is created. This problem is not serious in general, but if you create multiple composite indexes on a large table, the index file will expand very quickly.

Indexes are only a factor to improve efficiency. If your MySQL database has a large data volume of tables, you need to spend time researching and creating the best indexes or optimizing query statements.

(7) Notes on using Indexes

Tips and notes for using indexes:

◆ The index does not contain columns with NULL values.

As long as a column contains a NULL value, it will not be included in the index. If a column in the composite index contains a NULL value, this column is invalid for this composite index. Therefore, do not set the default value of a field to NULL during database design.

◆ Use short Indexes

Index a string or column. If possible, specify a prefix length. For example, if a CHAR (255) Column exists and multiple values are unique within the first 10 or 20 characters, do not index the entire column. Short indexes not only increase query speed, but also save disk space and I/O operations.

◆ Sorting of index Columns

MySQL queries only use one index. Therefore, if an index is already used in the where clause, columns in order by will not use the index. Therefore, do not use the sorting operation when the database's default sorting can meet the requirements. Try not to include the sorting of multiple columns. It is best to create a composite index for these columns if necessary.

◆ Like statement operation

Generally, like operations are not encouraged. If they are not usable, how to use them is also a problem. Like "% aaa %" does not use indexes, but like "aaa %" can use indexes.

◆ Do not perform operations on columns

 
 
  1. select * from users where YEAR(adddate)<2007;

The operation will be performed on each row, which will cause index failure and scan the entire table, so we can change it

 
 
  1. select * from users where adddate<‘2007-01-01’;

◆ Do NOT use not in and <> operations

The above section describes the MySQL index type.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.